https://www.acmicpc.net/problem/10384

 

10384번: 팬그램

팬그램은 모든 알파벳을 적어도 한 번씩을 사용한 영어 문장을 말한다. 다음은 유명한 팬그램 중 하나이다. The quick brown fox jumps over a lazy dog 더블 팬그램은 모든 알파벳을 적어도 두 번씩은 사용

www.acmicpc.net

A~Z까지 key로 만들어주고 key 값을 계속 돌면서 세주었다.

Pangram의 수를 어떻게 셀지 고민했는데 제일 작은 수를 출력하면 되는 거였다..

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int cnt = Integer.parseInt(bf.readLine());

        HashMap<Character, Integer> az = new HashMap<>();
        for (int i = 'a'; i <= 'z'; i++) {
            az.put((char) i, 0);
        }
        for (int i = 0; i < cnt; i++) {
            String str = bf.readLine();
            str = str.toLowerCase();
            HashMap<Character, Integer> map = new HashMap<>();
            for (int j = 0; j < str.length(); j++) {
                for (Character c : az.keySet()) {
                    if (str.charAt(j) == c) {
                        map.put(c, map.getOrDefault(c, 0) + 1);
                        break;
                    }
                }
            }
            int min = Integer.MAX_VALUE;
            for (Character c : az.keySet()) {
                if (map.getOrDefault(c, 0) == 0) {
                    min = 0;
                    break;
                }else{
                    if(min > map.get(c)){
                        min = map.get(c);
                    }
                }
            }
            if(min >=3){
                System.out.println("Case " + (i+1) + ": Triple pangram!!!");
            }else if(min == 2){
                System.out.println("Case " + (i+1) + ": Double pangram!!");
            }else if(min == 1){
                System.out.println("Case " + (i+1) + ": Pangram!");
            }else{
                System.out.println("Case " + (i+1) + ": Not a pangram");
            }
        }
    }
}

'알고리즘' 카테고리의 다른 글

[백준] 7569번 : 토마토  (0) 2023.03.06
[백준] 16499번 : 동일한 단어 그룹화하기  (0) 2023.03.05
[백준] 1439번 : 뒤집기  (0) 2023.03.04
[백준] 17413번 : 단어 뒤집기 2  (0) 2023.03.03
[백준] 14490번 : 백대열  (1) 2023.02.27

https://www.acmicpc.net/problem/7569

 

7569번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100,

www.acmicpc.net

머리의 한계로 3차 배열을 상상하는 거조차 어려웠던 거 같다..

pair 함수를 만들어서 사용하는데 출력 순서가 달라서 헷갈렸던 거 같다.

처음에 만든 방법은 그때그때마다 검사를 해줘서 시간 초과가 떴다.

import java.io.*;
import java.util.*;

public class Main {

	static int[] dx = { -1, 0, 1, 0 };
	static int[] dy = { 0, 1, 0, -1 };
	static int[] dh = { -1, 1 };
	static boolean[][][] visited = new boolean[101][101][101];
	static int[][][] map = new int[101][101][101];
	static int N, M, H;

	static Queue<pair> q = new LinkedList<>();

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		H = sc.nextInt();

		for (int k = 0; k < H; k++) {
			for (int i = 0; i < M; i++) {
				for (int j = 0; j < N; j++) {
					map[k][j][i] = sc.nextInt();
				}
			}
		}

		for (int k = 0; k < H; k++) {
			for (int i = 0; i < M; i++) {
				for (int j = 0; j < N; j++) {
					if (map[k][j][i] == 1) {
						q.add(new pair(i, j, k));
						visited[k][j][i] = true;
					}
				}
			}
		}

		System.out.println(bfs());
	}

	static boolean zeroCountFunc() {
		for (int k = 0; k < H; k++) {
			for (int i = 0; i < M; i++) {
				for (int j = 0; j < N; j++) {
					if (map[k][j][i] == 0) {
						return false;
					}
				}
			}
		}
		return true;
	}

	static class pair {
		int x;
		int y;
		int h;

		pair(int x, int y, int h) {
			this.x = x;
			this.y = y;
			this.h = h;
		}
	}

	static int bfs() {
		int cnt = 0;
		while (!q.isEmpty()) {
			cnt++;
			//print();
			int qSize = q.size();
			for (int o = 0; o < qSize; o++) {
				// 상하좌우
				for (int i = 0; i < 4; i++) {
					int nx = q.peek().x + dx[i];
					int ny = q.peek().y + dy[i];
					if (nx < 0 || nx > M - 1 || ny < 0 || ny > N - 1)
						continue;
					if (!visited[q.peek().h][ny][nx] && map[q.peek().h][ny][nx] == 0) {
						visited[q.peek().h][ny][nx] = true;
						map[q.peek().h][ny][nx] = 1;
						q.add(new pair(nx, ny, q.peek().h));
					}
				}
				// 위아래
				for (int i = 0; i < 2; i++) {
					int nh = q.peek().h + dh[i];
					if (nh < 0 || nh > H - 1)
						continue;
					if (!visited[nh][q.peek().y][q.peek().x] && map[nh][q.peek().y][q.peek().x] == 0) {
						visited[nh][q.peek().y][q.peek().x] = true;
						map[nh][q.peek().y][q.peek().x] = 1;
						q.add(new pair(q.peek().x, q.peek().y, nh));
					}
				}
				q.poll();
			}
		}
		if (!zeroCountFunc()) {
			return -1;
		} else {
			return cnt - 1;
		}
	}

	static void print() {
		for (int k = 0; k < H; k++) {
			for (int i = 0; i < M; i++) {
				for (int j = 0; j < N; j++) {
					System.out.print(map[k][j][i] + " ");
				}
				System.out.println();
			}
			System.out.println("==============================");
		}
	}
}

 

'알고리즘' 카테고리의 다른 글

[백준] 10384번 : 팬그램  (0) 2023.03.11
[백준] 16499번 : 동일한 단어 그룹화하기  (0) 2023.03.05
[백준] 1439번 : 뒤집기  (0) 2023.03.04
[백준] 17413번 : 단어 뒤집기 2  (0) 2023.03.03
[백준] 14490번 : 백대열  (1) 2023.02.27

https://www.acmicpc.net/problem/16499

 

16499번: 동일한 단어 그룹화하기

첫째 줄에 단어의 개수 N이 주어진다. (2 ≤ N ≤ 100) 둘째 줄부터 N개의 줄에 단어가 한 줄에 하나씩 주어진다. 단어는 알파벳 소문자로만 이루어져 있고, 길이는 10을 넘지 않는다.

www.acmicpc.net

toCharArray 함수는 처음 써보는 거 같다.

Arrays로는 정렬을 안 돌려서

보통은 ArrayList를 선언해서 Collection으로만 정렬시키는데

여러 함수를 자주 써보려고 노력해야겠다.

import java.io.*;
import java.util.*;


public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int cnt = Integer.parseInt(bf.readLine());
        HashMap<String, Integer> map = new HashMap<>();
        for (int i = 0; i < cnt; i++) {
            String str = bf.readLine();
            char[] chars = str.toCharArray();
            Arrays.sort((chars));
            str = new String(chars);
            map.put(str, 0);
        }
        System.out.println(map.size());
    }
}

 

'알고리즘' 카테고리의 다른 글

[백준] 10384번 : 팬그램  (0) 2023.03.11
[백준] 7569번 : 토마토  (0) 2023.03.06
[백준] 1439번 : 뒤집기  (0) 2023.03.04
[백준] 17413번 : 단어 뒤집기 2  (0) 2023.03.03
[백준] 14490번 : 백대열  (1) 2023.02.27

https://www.acmicpc.net/problem/1439

 

1439번: 뒤집기

다솜이는 0과 1로만 이루어진 문자열 S를 가지고 있다. 다솜이는 이 문자열 S에 있는 모든 숫자를 전부 같게 만들려고 한다. 다솜이가 할 수 있는 행동은 S에서 연속된 하나 이상의 숫자를 잡고 모

www.acmicpc.net

하.. 골드 문제 건드렸다가 4시간 걸려서 풀었구먼 시간 초과가 뜬다..

제출을 위해서 한 문제를 풀었다.. 아니면 벌금이라..

그리드로 풀라고 만든 문젠데 조건이 0,1뿐이라 해시 맵으로 이상하게 풀었다..

import java.io.*;
import java.util.*;


public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str = bf.readLine();
        HashMap<Character, Integer> map = new HashMap<>();
        Character temp = str.charAt(0);
        map.put(temp, 1);
        for (int i = 0; i < str.length(); i++) {
            if (temp != str.charAt(i)) {
                temp = str.charAt(i);
                if (str.charAt(i) == '0') {
                    map.put(str.charAt(i), map.getOrDefault(str.charAt(i), 0) + 1);
                } else {
                    map.put(str.charAt(i), map.getOrDefault(str.charAt(i), 0) + 1);
                }
            }
        }
        if (map.getOrDefault('0', 0) > map.getOrDefault('1', 0)) {
            System.out.println(map.getOrDefault('1', 0));
        } else {
            System.out.println(map.getOrDefault('0', 0));
        }
    }
}

 

https://www.acmicpc.net/problem/17413

 

17413번: 단어 뒤집기 2

문자열 S가 주어졌을 때, 이 문자열에서 단어만 뒤집으려고 한다. 먼저, 문자열 S는 아래와과 같은 규칙을 지킨다. 알파벳 소문자('a'-'z'), 숫자('0'-'9'), 공백(' '), 특수 문자('<', '>')로만 이루어져

www.acmicpc.net

변수도 많이 쓰고 생각보다 조건들이 까다로웠다 쉬운 문제라고 빨리 끝내야지 했는데..

조건식만 욱여넣어서 맞춘 기분이다..

import java.io.*;
import java.util.*;

public class Main {

	static ArrayList<String> arrStr = new ArrayList<>();
	public static void main(String[] args) throws Exception {
		int start = 0;
		int end = 0;
			
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String str = bf.readLine();
		String strTemp = "";
		Stack<Character> stack = new Stack<Character>();

		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == '<') {
				if (strTemp != "") {
					function(strTemp);
					strTemp = "";
				}
				start = i;
				stack.add(str.charAt(i));

			} else if (str.charAt(i) == '>') {
				end = i + 1;
				arrStr.add(str.substring(start, end));
				stack.pop();
				continue;
			}
			if (!stack.isEmpty()) {
				continue;
			}
			strTemp += str.charAt(i);
			if (i == str.length() - 1 && strTemp != "") {
				function(strTemp);
				strTemp = "";
			}
		}

		for (int i = 0; i < arrStr.size(); i++) {
			System.out.print(arrStr.get(i));
		}
	}

	static void function(String str) {
		StringBuffer sb;
		int startIndex = 0;
		int endIndex = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == ' ' || i == str.length() - 1) {
				if (i == str.length() - 1)
					i++;
				endIndex = i;
				sb = new StringBuffer(str.substring(startIndex, endIndex));
				arrStr.add(sb.reverse().toString());
				startIndex = i + 1;
				if (i != str.length()) {
					arrStr.add(" ");
				}
			}
		}
	}
}

https://www.acmicpc.net/problem/14490

 

14490번: 백대열

n과 m이 :을 사이에 두고 주어진다. (1 ≤ n, m ≤ 100,000,000)

www.acmicpc.net

조건에 겹치는 부분이 있는 거 같다.. 최대한 줄이려고 노력해야겠다.

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {

        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str = bf.readLine();
        int n = 0;
        int m = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ':') {
                n = Integer.parseInt(str.substring(0, i));
                m = Integer.parseInt(str.substring(i + 1, str.length()));
                break;
            }
        }
        int divide = 2;
        while (true) {
            if (n < 2 || m < 2) {
                System.out.print(n + ":" + m);
                break;
            }
            if (n % divide == 0 && m % divide == 0) {
                n /= divide;
                m /= divide;
                if (n == 1 || m == 1) {
                    System.out.print(n + ":" + m);
                    break;
                }
            } else {
                divide++;
                if (divide >= n && divide >= m) {
                    System.out.print(n + ":" + m);
                    break;
                }
            }
        }
    }
}

'알고리즘' 카테고리의 다른 글

[백준] 1439번 : 뒤집기  (0) 2023.03.04
[백준] 17413번 : 단어 뒤집기 2  (0) 2023.03.03
[백준] 10026번 : 적록색약  (0) 2023.02.26
[백준] 4949번 : 균형잡힌 세상  (0) 2023.02.25
[백준] 4963번 : 섬의 개수  (0) 2023.02.24

+ Recent posts