목차
백준 단계별로 풀어보기
25.11.01
14단계: 집합과 맵
10816번: 숫자 카드 2
문제 링크 : https://www.acmicpc.net/problem/10816
문제를 풀기 위해 알아야 할 개념
>> Dictionary.TryAdd(Key, Value)
: 지정된 키와 값을 Dictionary에 추가하려고 시도한다. --> Dictionary에 키와 값이 성공적으로 추가되었다면 true, 그렇지 않으면 false를 반환한다.
※ 공식 문서 - Dictionary.TryAdd(TKey, TValue)
Dictionary<TKey,TValue>.TryAdd(TKey, TValue) 메서드 (System.Collections.Generic)
지정된 키와 값을 사전에 추가하려고 시도합니다.
learn.microsoft.com
문제 풀이
- StreamReader로 입력값을 받아 int값으로 변환하여 상근이가 가진 숫자 카드의 개수를 담을 변수 n 에 담고, 숫자 카드에 적힌 수를 입력받아 string형 배열 numN 에 담고, 카드에 적힌 수를 Key, 개수를 Value로 담을 Dicitonary dict 를 초기화한다.
- for 반복문을 통해 numN 에 담긴 수를 int값으로 변환하여 임시 변수인 temp 에 담은 후, TryAdd 함수를 통해 temp 가 dict 에 없다면 값을 1로 추가하고, 있다면 temp 를 Key로 갖는 값을 1 증가시킨다.
- StreamReader로 입력값을 받아 int값으로 변환하여 주어지는 수의 개수를 담을 변수 m 에 담고, 그 수들을 입력받아 string형 배열 numM 에 담는다.
- for 반복문을 통해 numM 에 담긴 수를 int값으로 변환하여 임시 변수인 temp 에 담은 후, TryGetValue 함수를 통해 temp 가 dict 에 있다면 count 에 값을 받아서 StringBuilder에 count 를 담고, 없다면 StringBuilder에 '0' 을 담는다.
- StringBuilder에 담은 값을 출력한다.
정답 코드
using System.IO;
using System.Text;
class Backjoon
{
static void Main(string[] args)
{
using var sr = new StreamReader(Console.OpenStandardInput());
using var sw = new StreamWriter(Console.OpenStandardOutput());
StringBuilder sb = new StringBuilder();
int n = int.Parse(sr.ReadLine());
string[] numN = sr.ReadLine().Split();
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int i = 0; i < n; i++)
{
int temp = int.Parse(numN[i]);
if (!dict.TryAdd(temp, 1))
dict[temp]++;
}
int m = int.Parse(sr.ReadLine());
string[] numM = sr.ReadLine().Split();
for (int i = 0; i < m; i++)
{
int temp = int.Parse(numM[i]);
if (dict.TryGetValue(temp, out int count))
sb.Append(count).Append(' ');
else
sb.Append('0').Append(' ');
}
sw.Write(sb.ToString().TrimEnd());
}
}'Development > Baekjoon' 카테고리의 다른 글
| [C#] 1269번: 대칭 차집합 (0) | 2025.11.03 |
|---|---|
| [C#] 1764번: 듣보잡 (0) | 2025.11.02 |
| [C#] 1620번: 나는야 포켓몬 마스터 이다솜 (0) | 2025.10.31 |
| [C#] 7785번: 회사에 있는 사람 (0) | 2025.10.30 |
| [C#] 14425번: 문자열 집합 (0) | 2025.10.29 |