๋ฌธ์ (์ถ์ฒ: 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] 15044_Fase (0) | 2025.02.14 |
---|---|
[Baekjoon] 15081_Is Everybody Appy? (0) | 2025.02.13 |
[Baekjoon] 4368_Babelfish (0) | 2025.02.11 |
[Baekjoon] 4675_Word Amalgamation (0) | 2025.02.10 |
[Baekjoon] 18706_Coffee (0) | 2025.02.07 |