Problem Solving/Baekjoon
[백준] 11235 Polling - Data Structure / Java
graycode
2023. 9. 11. 21:11
• 문제 링크
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();
}
}