๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 23843_์ฝ˜์„ผํŠธ

๋ฟŒ์•ผ._. 2023. 8. 31. 09:15

Gold V

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/23843)

< ์ฝ˜์„ผํŠธ >

 

๋ฌธ์ œ ํ’€์ด 

 

๊ฐ’์ด ํฐ ๊ฒƒ์„ ์šฐ์„ ์œผ๋กœ ํ•˜๋Š” ์šฐ์„ ์ˆœ์œ„ ํ A์— ์ถฉ์ „์— ํ•„์š”ํ•œ ์‹œ๊ฐ„์„ ์ €์žฅํ•œ๋‹ค.(=์ถฉ์ „ ์‹œ๊ฐ„์ด ๋งŽ์€ ์ˆœ๋Œ€๋กœ ์ •๋ ฌ)

๊ฐ’์ด ์ž‘์€ ๊ฒƒ์„ ์šฐ์„ ์œผ๋กœ ํ•˜๋Š” ์šฐ์„ ์ˆœ์œ„ ํ B์— A๋ฅผ ์ฝ˜์„ผํŠธ ๊ฐœ์ˆ˜๋งŒํผ ๋„ฃ์–ด์ค€๋‹ค.

์ถฉ์ „ ์‹œ๊ฐ„์„ ๊ณ„์‚ฐํ•ด ์ค€๋‹ค. 

 

 

 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.PriorityQueue;
import java.util.StringTokenizer;

public class _23843_ { // ์ฝ˜์„ผํŠธ

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(bf.readLine());

		int n = Integer.parseInt(st.nextToken());
		int m = Integer.parseInt(st.nextToken());

		st = new StringTokenizer(bf.readLine());
		PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
		for (int i = 0; i < n; i++) {
			queue.add(Integer.parseInt(st.nextToken()));
		}

		PriorityQueue<Integer> socket = new PriorityQueue<>();
		ArrayList<Integer> list = new ArrayList<>();
		int result = 0, num=0;
		while (!queue.isEmpty()) {
			if (socket.size() < m) {
				socket.add(queue.poll());
			} else {
				num=socket.poll();
				result += num;
				while(!socket.isEmpty()) {
					int x =socket.poll()-num;
					if(x>0) {
						list.add(x);
					}
				}
				for(int i=0; i<list.size(); i++) {
					socket.add(list.get(i));
				}
				list.clear();
			}
		}

		while(!socket.isEmpty()) {
			num=socket.poll();
		}
		result+=num;

		System.out.println(result);
	}
}

 

Main

๋ณ€์ˆ˜)
n : ์ „์ž๊ธฐ๊ธฐ์˜ ๊ฐœ์ˆ˜
m : ์ฝ˜์„ผํŠธ ๊ฐœ์ˆ˜
queue : PriorityQueue <Integer> ์ถฉ์ „์— ํ•„์š”ํ•œ ์‹œ๊ฐ„ ์ €์žฅ (๋‚ด๋ฆผ์ฐจ์ˆœ)
socket : PriorityQueue <Integer> ์ฝ˜์„ผํŠธ (์˜ค๋ฆ„์ฐจ์ˆœ)
result : ์ถฉ์ „์— ํ•„์š”ํ•œ ์ตœ์†Œ ์‹œ๊ฐ„
num : ๊ฐ’ ์ €์žฅํ•˜๋Š” ๋ณ€์ˆ˜

 

- ์ „์ž๊ธฐ๊ธฐ์˜ ๊ฐœ์ˆ˜(n), ์ฝ˜์„ผํŠธ ๊ฐœ์ˆ˜(m) ์ž…๋ ฅ

- ์ถฉ์ „์— ํ•„์š”ํ•œ ์‹œ๊ฐ„ n๊ฐœ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ queue์— ์ €์žฅ

- queue๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต

: socket์˜ ํฌ๊ธฐ๊ฐ€ ์ฝ˜์„ผํŠธ์˜ ๊ฐœ์ˆ˜(m) ๋ณด๋‹ค ์ž‘๋‹ค๋ฉด ์ถฉ์ „ํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ queue์—์„œ poll ํ•ด์„œ socket์— ์ €์žฅ

: socket์˜ ํฌ๊ธฐ๊ฐ€ ์ฝ˜์„ผํŠธ ๊ฐœ์ˆ˜๋ผ๋ฉด socket์—์„œ ๊ฐ’์„ poll ํ•ด์„œ ์ถฉ์ „์‹œํ‚ด

: ์ถฉ์ „์‹œํ‚ค๋ฉด socket์— ์žˆ๋˜ ๋‚˜๋จธ์ง€ ์ „์ž๊ธฐ๊ธฐ๋„ ๊ทธ๋งŒํผ ์ถฉ์ „๋ผ์•ผ ํ•˜๋ฏ€๋กœ ๋‹ค poll ํ•ด์„œ ์•ž์—์„œ ์ถฉ์ „ํ•œ ๋งŒํผ ๋นผ์„œ ๋‹ค์‹œ socket์— ์ €์žฅ

- ๋งˆ์ง€๋ง‰์— ์ถฉ์ „๋˜๋Š” ์ „์ž๊ธฐ๊ธฐ๋Š” socket์˜ ๋งˆ์ง€๋ง‰ ๊ฐ’์ด ์ตœ๋Œ“๊ฐ’์ด๋ฏ€๋กœ ๋‹ค poll ํ•œ ํ›„ ๋งˆ์ง€๋ง‰ ๊ฐ’๋งŒ result์— ๋”ํ•จ

- ์ถฉ์ „์— ํ•„์š”ํ•œ ์ตœ์†Œ ์‹œ๊ฐ„(result) ์ถœ๋ ฅ