๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 15903_์นด๋“œ ํ•ฉ์ฒด ๋†€์ด

๋ฟŒ์•ผ._. 2023. 7. 2. 23:39

Silver I

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

< ์นด๋“œ ํ•ฉ์ฒด ๋†€์ด >

 

๋ฌธ์ œ ํ’€์ด 

 

๊ฐ€์žฅ ์ž‘์€ ์ ์ˆ˜๋ฅผ ์–ป๊ธฐ ์œ„ํ•ด ์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ž‘์€ ์ˆ˜๋ฅผ ๋ฝ‘์•„ ๋”ํ•œ๋‹ค.

๋”ํ•  ๋•Œ int ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ long์œผ๋กœ ์„ ์–ธํ•œ๋‹ค.

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class _15903_ { // ์นด๋“œ ํ•ฉ์ฒด ๋†€์ด

	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());

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

		for (int i = 0; i < m; i++) {
			long x = queue.poll();
			long y = queue.poll();
			queue.add(x + y);
			queue.add(x + y);
		}

		long result = 0;
		while (!queue.isEmpty()) {
			result += queue.poll();
		}
		System.out.println(result);
	}
}

 

Main

๋ณ€์ˆ˜)
n : ์นด๋“œ์˜ ๊ฐœ์ˆ˜
m : ์นด๋“œ ํ•ฉ์ฒด๋ฅผ ๋ช‡ ๋ฒˆ ํ•˜๋Š”์ง€ ๋‚˜ํƒ€๋‚ด๋Š” ์ˆ˜
queue : ์นด๋“œ์˜ ์ƒํƒœ๋ฅผ ์ €์žฅ
result : ๊ฐ€์žฅ ์ž‘์€ ์ ์ˆ˜

 

- ์นด๋“œ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ˆ˜ (n)๊ณผ ์นด๋“œ ํ•ฉ์ฒด๋ฅผ ๋ช‡ ๋ฒˆ ํ•˜๋Š”์ง€๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ˆ˜ (m) ์ž…๋ ฅ

- ์šฐ์„ ์ˆœ์œ„ ํ์— ์นด๋“œ์˜ ์ƒํƒœ๋ฅผ ์ €์žฅ

- ์šฐ์„ ์ˆœ์œ„ ํ ์ด๋ฏ€๋กœ ๋ฝ‘์•„๋‚ด๋ฉด ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜์ด๋‹ค. ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜ ๋‘ ๊ฐœ๋ฅผ ๋”ํ•ด์„œ queue์— ๋‘ ๋ฒˆ ์ €์žฅ

- ์šฐ์„ ์ˆœ์œ„ ํ์— ์žˆ๋Š” ๊ฐ’์„ ๋‹ค ๋ฝ‘์•„๋‚ด์„œ ๋”ํ•œ ๊ฐ’(result)์„ ์ถœ๋ ฅ