• 문제 링크
11235번: Polling
Output the name of the candidate with the most votes. If there is a tie, output out all of the names of candidates with the most votes, one per line, in alphabetical order. Do not output any spaces, and do not output blank lines between names.
www.acmicpc.net
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
Map<String, Integer> map = new HashMap<>();
String s;
int n = Integer.parseInt(br.readLine());
while (n-- > 0) map.put(s = br.readLine(), map.getOrDefault(s, 0) + 1);
Pair[] arr = new Pair[map.size()];
for (String key : map.keySet()) arr[++n] = new Pair(key, map.get(key));
Arrays.sort(arr);
n = 0;
for (Pair p : arr) {
if (p.value < n) break;
sb.append(p.key).append("\n");
n = p.value;
}
bw.write(sb.toString());
bw.flush();
}
private static class Pair implements Comparable<Pair> {
String key;
int value;
public Pair(String key, int value) {
this.key = key;
this.value = value;
}
@Override
public int compareTo(Pair o) {
return o.value != value ? o.value - value : key.compareTo(o.key);
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
Map<String, Integer> map = new TreeMap<>();
String s;
int n = Integer.parseInt(br.readLine()), max = 0;
while (n-- > 0) {
map.put(s = br.readLine(), map.getOrDefault(s, 0) + 1);
max = Math.max(max, map.get(s));
}
for (String key : map.keySet()) if (map.get(key) == max) sb.append(key).append("\n");
bw.write(sb.toString());
bw.flush();
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 11370 Spawn of Ungoliant - Graph Theory / Java (0) | 2023.09.13 |
---|---|
[백준] 14544 Vote - Data Structure / Java (0) | 2023.09.12 |
[백준] 16815 Star in Parentheses - Data Structure / Java (0) | 2023.09.10 |
[백준] 18679 Banana - Data Structure / Java (0) | 2023.09.09 |
[백준] 5089 Travelling Salesman - Data Structure / Java (0) | 2023.09.08 |
댓글