๋ฌธ์ (์ถ์ฒ: https://www.acmicpc.net/problem/25325)
< ํ์ ์ธ๊ธฐ๋ ์ธก์ >
๋ฌธ์ ํ์ด
HashMap์ ํ์ฉํ์ฌ ํด๋น ํ์์ ์ข์ํ๋ ํ์ ์๋ฅผ ๊ตฌํ๋ค. ArrayList์ ํ์ ์ด๋ฆ๊ณผ ์ธ๊ธฐ๋๋ฅผ ์ ์ฅํ๋ค. ์ธ๊ธฐ๋ ๊ธฐ์ค์ผ๋ก ๋ด๋ฆผ์ฐจ์, ์ธ๊ธฐ๋๊ฐ ๊ฐ๋ค๋ฉด ํ์ ์ด๋ฆ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌ ํ ์ถ๋ ฅํ๋ค.
my solution (Java)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;
public class _25325_ { // ํ์ ์ธ๊ธฐ๋ ์ธก์
static class Student implements Comparable<Student> {
private String name;
private int score;
public Student(String name, int score) {
this.name=name;
this.score=score;
}
@Override
public int compareTo(Student o) {
if (o.score == this.score) {
return this.name.compareTo(o.name);
}
return o.score - this.score;
}
}
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
int n = Integer.parseInt(bf.readLine());
HashMap<String, Integer> map = new HashMap<>();
st = new StringTokenizer(bf.readLine());
for (int i = 0; i < n; i++) {
map.put(st.nextToken(), 0);
}
for (int i = 0; i < n; i++) {
st = new StringTokenizer(bf.readLine());
while (st.hasMoreTokens()) {
String name = st.nextToken();
map.replace(name, map.get(name) + 1);
}
}
ArrayList<Student> list = new ArrayList<>();
for (String name : map.keySet()) {
list.add(new Student(name, map.get(name)));
}
Collections.sort(list);
for(int i=0; i<n; i++) {
bw.write(list.get(i).name+" "+list.get(i).score+"\n");
}
bw.flush();
}
}
๋ณ์)
n : ํ์ ์
map : HashMap <ํ์ ์ด๋ฆ, ์ธ๊ธฐ๋>
list : ArrayList <ํ์>
ํ์ ์๋ฅผ ์ ๋ ฅ๋ฐ๋๋ค. ํ์ ์๋งํผ ์ด๋ฆ์ ์ ๋ ฅ๋ฐ์ HashMap์ ์ด๋ฆ๊ณผ 0์ ๊ฐ๊ฐ key, value๋ก ์ ์ฅํ๋ค. ํ์ ์๋งํผ ํ์์ ์ ๋ณด๋ฅผ ์ ๋ ฅ๋ฐ์ value๋ฅผ ์ฆ๊ฐ์ํจ๋ค.
HashMap ๊ฐ์ ArrayList์ ์ด๋ฆ๊ณผ ์ธ๊ธฐ๋๋ฅผ ๋ณ์๋ก ๊ฐ์ง๋ Student๋ก ์ ์ฅํ๋ค. ์ธ๊ธฐ๋ ๊ธฐ์ค์ผ๋ก ๋ด๋ฆผ์ฐจ์, ์ธ๊ธฐ๋๊ฐ ๊ฐ๋ค๋ฉด ์ด๋ฆ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌ ํ ArrayList ๊ฐ์ ์ถ๋ ฅํ๋ค.

'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Baekjoon] 29891_์ฒดํฌํฌ์ธํธ ๋ฌ๋ฆฌ๊ธฐ (0) | 2024.06.13 |
---|---|
[Baekjoon] 23246_Sport Climbing Combined (0) | 2024.06.12 |
[Baekjoon] 15702_์ค๊ฐ๊ณ ์ฌ ์ฑ์ (0) | 2024.06.10 |
[Baekjoon] 11971_์๋ ์๋ฐ (0) | 2024.06.07 |
[Baekjoon] 1384_๋ฉ์์ง (0) | 2024.06.06 |