본문 바로가기

컴퓨터&프로그래밍/Baekjoon

[백준/C#] 10816 - 숫자 카드 2

1. 문제

 

- 입력

첫째 줄 : N

둘째 줄 : N개의 숫자 카드 (정수)

셋째 줄 : M

넷째 줄 : 상근이가 몇 개 가지고 있는 숫자카드인지 구해야 할 M개의 정수

 

1 ≤ N, M ≤ 500,000

-10,000,000 ≤ 숫자 카드 정수 ≤ 10,000,000

- 출력

첫째 줄에 입력으로 주어진 M개의 수에 대해서, 각 수가 적힌 숫자 카드를 상근이가 몇 개 가지고 있는지를 공백으로 구분해 출력한다.

- 설명

예제 입력 예제 출력
10
6 3 2 10 10 10 -10 -10 7 3
8
10 9 -5 2 3 4 5 -10
10
6 3 2 10 10 10 -10 -10 7 3
8
10 9 -5 2 3 4 5 -10

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

 

10816번: 숫자 카드 2

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

www.acmicpc.net


2. 풀이

귀찮아서 배열쓰고 Where(x=> x==mCards[i]).Count()썼더니 시간초과 당했다.

 

그래서 숫자가 키, 각 숫자 카드의 개수를 값으로 하는 딕셔너리를 만들어서 풀었다. 

// 숫자 카드
using (StreamReader sr = new StreamReader(Console.OpenStandardInput())) {
	// 입력받기
    int N = int.Parse(sr.ReadLine());
    int[] nInput = Array.ConvertAll(sr.ReadLine().Split(" "), int.Parse);
    Dictionary<int, int> nCards = new Dictionary<int, int>();
    for (int i = 0; i < N; i++) {
        if (nCards.ContainsKey(nInput[i])) nCards[nInput[i]]++;
        else nCards.Add(nInput[i], 1);
    }
    int M = int.Parse(sr.ReadLine());
    int[] mCards = Array.ConvertAll(sr.ReadLine().Split(" "), int.Parse);

	// 출력용 배열
    int[] output = new int[M];

    for (int i = 0; i < M; i++) {
        if (nCards.ContainsKey(mCards[i])) output[i] = nCards[mCards[i]];
    }

    using (StreamWriter sw = new StreamWriter(Console.OpenStandardOutput())) {
        sw.WriteLine(string.Join(" ", output).ToString());
    }

}



Calendar
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Visits
Today
Yesterday