2910번: 빈도 정렬
첫째 줄에 메시지의 길이 N과 C가 주어진다. (1 ≤ N ≤ 1,000, 1 ≤ C ≤ 1,000,000,000) 둘째 줄에 메시지 수열이 주어진다.
www.acmicpc.net
접근 : 정렬
1. map활용법에 익숙해지기 좋은 문제였다.
2. 주어진 조건을 통해 커스텀 정렬
Javascript
let input = require("fs")
.readFileSync("input.txt") //"/dev/stdin"
.toString()
.split("\n")
.map((val) => val.trim());
let [n, c] = input
.shift()
.split(" ")
.map((v) => +v);
let arr = input[0].split(" ").map((v) => +v);
function solution() {
let answer = [];
let hs = new Map();
for (let i = 0; i < n; i++) {
let temp = arr[i];
if (hs.has(temp)) {
let [cnt, idx] = hs.get(temp);
cnt++;
hs.set(temp, [cnt, idx]);
} else {
hs.set(temp, [1, i]);
}
}
let tmp = [];
for (const [key, val] of hs) {
tmp.push([key, val]);
}
tmp.sort((a, b) => {
if (a[1][0] === b[1][0]) return a[1][1] - b[1][1];
else return b[1][0] - a[1][0];
});
for (const [key, [cnt, idx]] of tmp) {
for (let i = 0; i < cnt; i++) {
answer.push(key);
}
}
console.log(answer.join(" "));
}
solution();
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
int n,c,a[1004];
vector<pair<int,int>> v;
map<int,int> m,mp;
bool cmp(pair<int,int> a, pair<int,int>b){
if(a.first==b.first) return mp[a.second] < mp[b.second];
return a.first>b.first;
}
int main()
{
freopen("input.txt", "r", stdin); //제출 시 삭제
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin>>n>>c;
for(int i=0;i<n;i++){
cin>>a[i];
m[a[i]]++;
if(mp[a[i]]==0) mp[a[i]]=i+1;
}
for(auto it:m){
v.push_back({it.second, it.first});
}
sort(v.begin(),v.end(),cmp);
for(auto i:v){
for(int j=0;j<i.first;j++){
cout<<i.second<<" ";
}
}
return 0;
}
'코딩테스트(알고리즘) > baekjoon' 카테고리의 다른 글
[baekjoon] 10819 차이를 최대로 (0) | 2022.11.08 |
---|---|
[baekjoon] 4659 비밀번호 발음하기 (Javascript,C++) (0) | 2022.07.12 |
[baekjoon] 2583 영역 구하기 (Javascript,c++) (0) | 2022.07.11 |
[baekjoon] 2468 안전영역 (Javascript, c++) (0) | 2022.07.05 |
[baekjoon] 1012 유기농 배추 (C++,Javascript) (0) | 2022.07.04 |