백준 알고리즘(C++)
백준 2910번 빈도 정렬 ( C++)
coding232624
2024. 3. 18. 20:59
문제
https://www.acmicpc.net/problem/2910
2910번: 빈도 정렬
첫째 줄에 메시지의 길이 N과 C가 주어진다. (1 ≤ N ≤ 1,000, 1 ≤ C ≤ 1,000,000,000) 둘째 줄에 메시지 수열이 주어진다.
www.acmicpc.net
해설
2가지 조건을 가지고 정렬을 하는 문제 => 커스텀 비교함수를 이용한 정렬
map / vector등을 반복문에 돌릴경우 auto
코드
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
#include <bits/stdc++.h>
using namespace std;
int n, c, tmp;
map<int, int> mp, mp_count;
vector<pair<int, int>> ret;
bool cmp(pair<int, int> a, pair<int, int> b)
{
if (a.second == b.second)
return mp[a.first] < mp[b.first];
else
return a.second > b.second;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> c;
for (int i = 0; i < n; i++)
{
cin >> tmp;
if (mp[tmp] == 0)
mp[tmp] = i + 1;
mp_count[tmp]++;
}
for (auto i : mp)
{
ret.push_back({i.first, mp_count[i.first]});
}
sort(ret.begin(), ret.end(), cmp);
for (auto a : ret)
{
for (int i = 0; i < a.second; i++)
{
cout << a.first << " ";
}
}
}
|
cs |