[BaekJoon] 20920번 - 영단어 암기는 괴로워 [Java][C++]
[BaekJoon] 20920번 - 영단어 암기는 괴로워 [Java][C++]
1. 문제 풀이
각 단어에 대해 단어가 중복 등장할 수 있으며 우선순위를 적용해 정렬을 해야하는 문제다. 단어의 등장 횟수를 구하기 위해 맵 자료구조를 활용해서 정렬을 해줬다.
2. 코드
1. 풀이 [Java]
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
45
46
47
48
49
50
51
import java.io.*;
import java.util.*;
public class Main {
static class Node implements Comparable<Node> {
String str;
int cnt;
public Node(String str, int cnt) {
this.str = str;
this.cnt = cnt;
}
@Override
public int compareTo(Node o) {
if (this.cnt != o.cnt) return Integer.compare(o.cnt, this.cnt);
if (this.str.length() != o.str.length()) return Integer.compare(o.str.length(), this.str.length());
return this.str.compareTo(o.str);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < N; i++) {
String str = br.readLine();
if (str.length() < M) continue;
map.put(str, map.getOrDefault(str, 0) + 1);
}
List<Node> list = new ArrayList<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
list.add(new Node(entry.getKey(), entry.getValue()));
}
list.sort(Comparator.naturalOrder());
for (Node node : list) {
bw.write(node.str);
bw.newLine();
}
bw.flush();
}
}
2. 풀이 [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
31
32
33
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
unordered_map<string, int> mp;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
if (s.size() < m) continue;
mp[s]++;
}
vector<pair<string, int>> v;
for (auto& [key, value] : mp) {
v.emplace_back(key, value);
}
sort(v.begin(), v.end(), [](auto& a, auto& b) {
if (a.second != b.second) return a.second > b.second;
if (a.first.size() != b.first.size()) return a.first.size() > b.first.size();
return a.first < b.first;
});
for (auto& x : v) {
cout << x.first << '\n';
}
}
This post is licensed under CC BY 4.0 by the author.