🌞Algorithm/πŸ”₯Baekjoon

[Baekjoon] 15323_ZigZag

λΏŒμ•Ό._. 2025. 6. 27. 17:11
문제(좜처: 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κ°’μœΌλ‘œ 문자λ₯Ό κ°€μ§€λŠ” μš°μ„ μˆœμœ„ 큐λ₯Ό μ°Ύμ•„ 첫 번째 값을 좜λ ₯ν•œλ‹€. κ·Έ ν›„ 선택 횟수λ₯Ό μ¦κ°€μ‹œμΌœ λ‹€μ‹œ μš°μ„ μˆœμœ„ 큐에 μ €μž₯ν•œλ‹€.