๋ฌธ์ (์ถ์ฒ: https://www.acmicpc.net/problem/15323)
< ZigZag >
๋ฌธ์ ํ์ด
๊ฐ ์ํ๋ฒณ์ ํด๋นํ๋ ์ฐ์ ์์ ํ๋ฅผ ๋ง๋ค์ด ๊ตฌ๋ถํ์ฌ ์ ์ฅํ๋ค. ๊ฐ ์ํ๋ฒณ์ผ๋ก ์์ํ๋ ๋จ์ด๋ค ์ค์์ ์ํ๋ฒณ ์์์ ์ ํ ํ์๋ฅผ ํ๋ณํ์ฌ ์ ํํ๋ค.
+ ๊ฐ ๋จ์ด์ ์์ํ๋ ์ํ๋ฒณ์ ๊ตฌ๋ถํ์ฌ ๋ฐ๋ก ์ ์ฅํ์ง ์๊ณ ํ ๋ฒ์ ์ ์ฅํ ๊ฒฝ์ฐ ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํ๋ค.
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.HashMap;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class _15323_ { // ZigZag
static class Word implements Comparable<Word> {
private String w;
private int count;
public Word(String w, int count) {
this.w = w;
this.count = count;
}
@Override
public int compareTo(Word o) {
if (this.count == o.count) {
return this.w.compareTo(o.w);
}
return this.count - o.count;
}
}
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 = new StringTokenizer(bf.readLine());
int k = Integer.parseInt(st.nextToken());
int n = Integer.parseInt(st.nextToken());
HashMap<Character, PriorityQueue<Word>> map = new HashMap<>();
for (int i = 0; i < 26; i++) {
map.put((char) ('a' + i), new PriorityQueue<>());
}
for (int i = 0; i < k; i++) {
String str = bf.readLine();
map.get(str.charAt(0)).add(new Word(str, 0));
}
for (int i = 0; i < n; i++) {
char x = bf.readLine().charAt(0);
Word word = map.get(x).poll();
bw.write(word.w + "\n");
word.count += 1;
map.get(x).add(word);
}
bw.flush();
}
}
๋ณ์)
k, n : ๋จ์ด, ๋ฌธ์ ๊ฐ์
map : HashMap <Character, PriorityQueue <Word>>
x : ๋ฌธ์
Word
๋จ์ด์ ์ ํ ํ์๋ฅผ ๋ณ์๋ก ๊ฐ์ง๋ฉฐ ์ ํ ํ์๊ฐ ์์์๋ก, ์ ํ ํ์๊ฐ ๊ฐ๋ค๋ฉด ์ํ๋ฒณ์์ผ๋ก ์ฐ์ ์์๋ฅผ ๊ฐ์ง๋ค.
Main
๋จ์ด์ ๋ฌธ์ ๊ฐ์๋ฅผ ์ ๋ ฅ๋ฐ๋๋ค. ๊ฐ ์ํ๋ฒณ์ ๋ฐ๋ผ ๊ตฌ๋ถํ์ฌ ์ ์ฅํ๊ธฐ ์ํด HashMap์ ์ํ๋ฒณ์ key ๊ฐ์ผ๋ก, PriorityQueue๋ฅผ value๋ก ์ ์ฅํ์ฌ ์ด๊ธฐํํ๋ค. ๋จ์ด ์๋งํผ ๋จ์ด๋ฅผ ์ ๋ ฅ๋ฐ์ ์์ํ๋ ์ํ๋ฒณ์ด ํด๋นํ๋ ๊ณณ์ ์ ์ฅํ๋ค. ๋ฌธ์ ๊ฐ์๋งํผ ๋ฌธ์๋ฅผ ์ ๋ ฅ๋ฐ์ map์์ key๊ฐ์ผ๋ก ๋ฌธ์๋ฅผ ๊ฐ์ง๋ ์ฐ์ ์์ ํ๋ฅผ ์ฐพ์ ์ฒซ ๋ฒ์งธ ๊ฐ์ ์ถ๋ ฅํ๋ค. ๊ทธ ํ ์ ํ ํ์๋ฅผ ์ฆ๊ฐ์์ผ ๋ค์ ์ฐ์ ์์ ํ์ ์ ์ฅํ๋ค.
'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Baekjoon] 16300_H to O (2) | 2025.07.08 |
---|---|
[Baekjoon] 26043_์๋น ๋ฉ๋ด (3) | 2025.07.07 |
[Baekjoon] 13732_Falling Apples (2) | 2025.06.26 |
[Baekjoon] 4881_์๋ฆฌ์์ ์ ๊ณฑ (0) | 2025.06.25 |
[Baekjoon] 19605_Cyclic Shifts (1) | 2025.06.24 |