ALGORITHM

백준 1715 카드 정렬하기 (Java)

공부하는_다온 2023. 5. 9. 22:20

1. 문제 링크

 

1715번: 카드 정렬하기

정렬된 두 묶음의 숫자 카드가 있다고 하자. 각 묶음의 카드의 수를 A, B라 하면 보통 두 묶음을 합쳐서 하나로 만드는 데에는 A+B 번의 비교를 해야 한다. 이를테면, 20장의 숫자 카드 묶음과 30장

www.acmicpc.net

 

2. 문제 및 입출력예제

 

3. 문제 풀이

1. A와 B를 합치려면 A+B번 비교해야 한다.

2. 작은 숫자 2개를 뽑아서 합치는 과정을 반복하면 된다.

3. PriorityQueue를 이용해서 2개를 뽑고 합을 다시 넣어서 다른 비교에 사용하도록 했다.

 

4. 코드

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

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(br.readLine());
		PriorityQueue<Integer> pq = new PriorityQueue<>();
		for(int i=0;i<N;i++) {
			pq.offer(Integer.parseInt(br.readLine()));
		} 
		
		int result = 0;
		while(pq.size() > 1) {
			int one = pq.poll();
			int two = pq.poll();
			result += one+two;
			pq.offer(one+two);
		}
		
		System.out.println(result);
	}
}