본문 바로가기

알고리즘/백준

1764 - 듣보잡(S4)

목차

    문제

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

    풀이

    HashSet으로 값을 추가한 후, contains를 사용하여 중복값을 확인.
    이후 중복값은 PriorityQueue를 통해 출력하였음.
    Class에 Comparator를 굳이 달 필요는 없었다.

    코드

    import java.util.*;
    import java.io.*;
    
    public class Main {
        static int N, M;
        static HashSet<String> hs = new HashSet<>();
        static PriorityQueue<String> pq = new PriorityQueue<>();
        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 = 0; i < N; i++) {
                hs.add(br.readLine());
            }
    
            for(int i = 0; i < M; i++) {
                StringBuilder now = new StringBuilder(br.readLine());
                if(hs.contains(now.toString())) pq.offer(now.toString());
            }
    
            //출력
            bw.write(pq.size() + "\n");
            while (!pq.isEmpty()) {
                bw.write(pq.poll() + "\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
    1620 - 나는야 포켓몬 마스터 이다솜(S4)  (1) 2023.10.24