본문 바로가기

알고리즘/백준

1620 - 나는야 포켓몬 마스터 이다솜(S4)

목차

    문제

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

    풀이

    Entry를 통해 전부 찾기보다는, TC가 10만개선이기 때문에 HashMap을 두 개 확보하여 GET을 통해 출력하게 하였다.

    try-catch문 사용하여 랜덤 문자열을 구분하였음.

    코드

    import java.util.*;
    import java.io.*;
    
    public class Main {
        static int N, M;
        static HashMap<Integer, String> hm = new HashMap<>();
        static HashMap<String, Integer> hm2 = new HashMap<>();
        public static void main(String[] args) throws Exception {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
            StringTokenizer st = new StringTokenizer(br.readLine());
            N = Integer.parseInt(st.nextToken());
            M = Integer.parseInt(st.nextToken());
    
            //반복문으로 해쉬맵에 값 넣기
            for (int i = 1; i <= N; i++) {
                StringBuilder now = new StringBuilder(br.readLine());
                hm.put(i, now.toString());
                hm2.put(now.toString(), i);
            }
    
            for (int i = 0; i < M; i++) {
                StringBuilder now = new StringBuilder(br.readLine());
                try {
                    //Int형으로 변환해서 된다면 코드에 맞는 값을 출력
                    int num = Integer.parseInt(now.toString());
                    bw.write(hm.get(num) + "\n");
                }
                catch (Exception e) {
                  	//아닐 경우 hm2릉 통해 값 출력
                    bw.write(hm2.get(now.toString()) + "\n");
                }
            }
    
    
            bw.close();
        }
    }

    '알고리즘 > 백준' 카테고리의 다른 글

    16928 - 뱀과사다리게임(G5)  (0) 2023.11.02
    17141 - 연구소(G4)  (0) 2023.11.02
    7576 - 토마토(G5)  (1) 2023.10.24
    7662 - 이중 우선순위 큐(G4)  (1) 2023.10.24
    1764 - 듣보잡(S4)  (0) 2023.10.24