본문 바로가기

알고리즘/백준

10816 - 숫자 카드 2[S4]

목차

    문제

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

     

    10816번: 숫자 카드 2

    첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,0

    www.acmicpc.net

     

    숫자 카드는 정수 하나가 적혀져 있는 카드이다. 상근이는 숫자 카드 N개를 가지고 있다. 정수 M개가 주어졌을 때, 이 수가 적혀있는 숫자 카드를 상근이가 몇 개 가지고 있는지 구하는 프로그램을 작성하시오.

    풀이

     

    해시맵으로 풀었으나, 이진 탐색의 방법이 원론적이라고 한다.

    다음에는 이진 탐색 역시 사용해볼 것..

     

    코드

     

    import java.util.*;
    import java.io.*;
    class Main {
        static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        static int N, M;
        public static void main(String[] args) throws Exception {
        	HashMap<Integer, Integer> hm = new HashMap<>(); 
        	
        	N = Integer.parseInt(br.readLine());
        	StringTokenizer st = new StringTokenizer(br.readLine());
        	while(st.hasMoreTokens()) {
        		int now = Integer.parseInt(st.nextToken());
        		if(hm.containsKey(now)) hm.put(now, hm.get(now) + 1);
        		else hm.put(now, 1);
        	}
        	
        	
        	M = Integer.parseInt(br.readLine());
        	st = new StringTokenizer(br.readLine());
        	while(st.hasMoreTokens()) {
        		int now = Integer.parseInt(st.nextToken());
        		
        		if(hm.containsKey(now)) bw.write(hm.get(now) + " ");
        		else bw.write("0 ");
        	}
        	
        	bw.close();
        }
    
    } //EOC

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

    10825 - 국영수[S4]  (2) 2023.12.08
    1654 - 랜선 자르기[S2]  (0) 2023.12.08
    11053 - 가장 긴 증가하는 부분 수열[S2]  (0) 2023.12.08
    9095 - 1,2,3 더하기[S3]  (1) 2023.12.08
    2805 나무자르기(S2)  (1) 2023.12.07