[백준 11652] 카드 (C#, C++) - soo:bak
작성일 :
문제 링크
설명
카드에 적힌 수들 중 가장 자주 등장한 수를 출력하는 문제입니다.
각 수는 \(-2^{62}\) 이상 \(2^{62}\) 미만의 정수로 주어지며, 동일한 수가 여러 번 등장할 수 있습니다.
가장 자주 등장한 수를 찾고,
만약 여러 개라면 그 중에서 가장 작은 수를 출력해야 합니다.
접근법
입력으로 주어진 모든 수에 대해 등장 횟수를 기록한 뒤, 가장 자주 등장한 수를 찾아야 합니다.
등장 횟수는 해시맵을 사용해 빠르게 계산할 수 있습니다.
최빈값이 여러 개일 경우에는 그중 가장 작은 수를 출력해야 하므로,
최대 빈도를 가진 수들을 모아 정렬한 뒤 가장 앞의 값을 선택합니다.
Code
C#
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
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
int n = int.Parse(Console.ReadLine());
var freq = new Dictionary<long, int>();
int maxFreq = 0;
for (int i = 0; i < n; i++) {
long num = long.Parse(Console.ReadLine());
if (!freq.ContainsKey(num))
freq[num] = 0;
freq[num]++;
if (freq[num] > maxFreq)
maxFreq = freq[num];
}
var result = freq
.Where(p => p.Value == maxFreq)
.Select(p => p.Key)
.Min();
Console.WriteLine(result);
}
}
C++
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
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef map<string, int> msi;
typedef vector<ll> vll;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
msi freq;
int maxCnt = 0;
while (n--) {
string s; cin >> s;
maxCnt = max(maxCnt, ++freq[s]);
}
vll candidates;
for (const auto& [key, val] : freq)
if (val == maxCnt)
candidates.push_back(stoll(key));
sort(candidates.begin(), candidates.end());
cout << candidates[0] << "\n";
return 0;
}