알고리즘/백준(BOJ)
[백준/알고리즘] #2910: 빈도 정렬
숲호랑이
2021. 10. 1. 23:43
https://www.acmicpc.net/problem/2910
2910번: 빈도 정렬
첫째 줄에 메시지의 길이 N과 C가 주어진다. (1 ≤ N ≤ 1,000, 1 ≤ C ≤ 1,000,000,000) 둘째 줄에 메시지 수열이 주어진다.
www.acmicpc.net
set를 이용해서 정렬할 줄 알면 되는 문제다.
파이썬 코드
#2910_빈도 정렬
import sys
input = sys.stdin.readline
N, C = map(int, input().split())
message = list(map(int, input().split()))
cnt = {}
for i in message:
if i not in cnt:
cnt[i]=0
cnt[i] += 1
cnt=sorted(cnt.items(), key=lambda x: x[1], reverse=True)
for key, value in cnt:
for i in range(value):
print(str(key), end=" ")
C++ 코드
#include <cstdio>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
int n, c, x;
map<int, int> mp;
map<int, int> m;
vector<pair<int, int> > p;
bool cmp(pair<int, int> a, pair<int, int> b) {
if (a.first == b.first) {
return m[a.second] < m[b.second];
}
return a.first > b.first;
}
int main() {
scanf("%d%d", &n, &c);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
mp[x]++;
if (!m[x])
m[x] = i + 1;
}
for (auto i : mp)
p.emplace_back(i.second, i.first);
sort(p.begin(), p.end(), cmp);
for (auto i : p) {
for (int j = 0; j < i.first; j++)
printf("%d ", i.second);
}
return 0;
}