정렬된 두 묶음의 숫자 카드가 있다고 하자. 각 묶음의 카드의 수를 A, B라 하면 보통 두 묶음을 합쳐서 하나로 만드는 데에는 A+B 번의 비교를 해야 한다. 이를테면, 20장의 숫자 카드 묶음과 30장의 숫자 카드 묶음을 합치려면 50번의 비교가 필요하다.
매우 많은 숫자 카드 묶음이 책상 위에 놓여 있다. 이들을 두 묶음씩 골라 서로 합쳐나간다면, 고르는 순서에 따라서 비교 횟수가 매우 달라진다. 예를 들어 10장, 20장, 40장의 묶음이 있다면 10장과 20장을 합친 뒤, 합친 30장 묶음과 40장을 합친다면 (10 + 20) + (30 + 40) = 100번의 비교가 필요하다. 그러나 10장과 40장을 합친 뒤, 합친 50장 묶음과 20장을 합친다면 (10 + 40) + (50 + 20) = 120 번의 비교가 필요하므로 덜 효율적인 방법이다.
N개의 숫자 카드 묶음의 각각의 크기가 주어질 때, 최소한 몇 번의 비교가 필요한지를 구하는 프로그램을 작성하시오.
from sys import stdin
from queue import PriorityQueue
pq=PriorityQueue()
for _ in range(int(stdin.readline().strip())):
pq.put(int(stdin.readline().strip()))
sum=0
while pq.qsize()>=2:
temp=pq.get()+pq.get()
sum+=temp
pq.put(temp)
print(sum)
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
PriorityQueue<Integer> pq=new PriorityQueue<>();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
int n=Integer.parseInt(br.readLine());
for(int i=0; i<n; i++)
pq.add(Integer.parseInt(br.readLine()));
int sum=0;
while(pq.size()>=2){
int temp=pq.poll()+pq.poll();
sum+=temp;
pq.add(temp);
}
bw.write(sum+"\n");
bw.flush();
}
}
문제를 보자마자 Matrix Chain Multiplication이 떠올랐다. 비슷한 맥락으로 Priority Queue를 만들어서 매회 가장 작은 두 카드팩끼리 더했다.