문제(출처: https://www.acmicpc.net/problem/4408)
< Election >
문제 풀이
HashMap에 key 값으로 후보자 이름을, value로 정당 이름을 저장한다.
또 다름 HashMap에 key 값으로 뽑힌 후보자 이름을, value로 뽑힌 횟수를 저장한다.
가장 많이 뽑힌 사람의 정당 이름을 구한다.
my solution (Java)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.StringTokenizer;
public class _4408_ { // Election
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int n = Integer.parseInt(bf.readLine());
HashMap<String, String> map = new HashMap<>();
for (int i = 0; i < n; i++) {
String name = bf.readLine();
String party = bf.readLine();
map.put(name, party);
}
int m = Integer.parseInt(bf.readLine());
HashMap<String, Integer> election = new HashMap<>();
for (int i = 0; i < m; i++) {
String name = bf.readLine();
if (map.containsKey(name)) {
if (election.containsKey(name)) {
election.put(name, election.get(name) + 1);
} else {
election.put(name, 1);
}
}
}
ArrayList<String> names = new ArrayList<>(election.keySet());
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return election.get(o2).compareTo(election.get(o1));
}
});
if (names.size() == 0) {
System.out.println("tie");
} else if (names.size() == 1) {
System.out.println(map.get(names.get(0)));
} else {
if (election.get(names.get(0)) == election.get(names.get(1))) {
System.out.println("tie");
} else {
System.out.println(map.get(names.get(0)));
}
}
}
}
변수)
n : 후보자 이름과 정당 이름의 수
map : HashMap <String, String>
m : 투표수
election : HashMap <String, Integer>
name : 뽑힌 후보자 이름
names : election HashMap의 key값 -> ArrayList
n을 입력받는다. n만큼 후보자 이름과 정당 이름을 입력받아 HashMap에 저장한다.
m을 입력받는다. m만큼 뽑힌 후보자 이름을 입력받아 HashMap에 뽑힌 횟수를 저장한다. 이때, 후보자에 없는 이름이라면 무시한다.
election HashMap의 key값을 ArrayList로 변환한 후 HashMap의 value 기준 내림차순으로 정렬한다. 만약 ArrayList의 크기가 0이라면 "tie"를 출력하고, 사이즈가 1이라면 당선자이므로 정당 이름을 출력한다. 그 외에는 최다 득표수인 후보자가 여러 명이라면 "tie"를, 한 명이라면 그 후보자의 정당 이름을 출력한다.
'🌞Algorithm > 🔥Baekjoon' 카테고리의 다른 글
[Baekjoon] 4368_Babelfish (0) | 2025.02.11 |
---|---|
[Baekjoon] 4675_Word Amalgamation (0) | 2025.02.10 |
[Baekjoon] 18706_Coffee (0) | 2025.02.07 |
[Baekjoon] 14455_Don't Be Last! (1) | 2025.02.06 |
[Baekjoon] 4351_Hay Points (1) | 2025.02.05 |