public class CardSort {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
PriorityQueue<Long> queue = new PriorityQueue<>();
for(int i = 0; i < N; i++) {
long num = (long)Integer.parseInt(br.readLine());
queue.offer(num);
}
long result = 0;
while(queue.size() > 1) {
long a = queue.poll();
long b = queue.poll();
result += (a + b);
queue.offer(a + b);
}
System.out.println(result);
}
}
ex) 10 20 40 50
turn1
a + b -> 10 + 20 = 30
sum -> 30
큐에 30을 다시 넣어준다.
turn2
a + b -> 30 + 40 = 70
sum -> 30 + 70 = 100
우선순위 큐이기 때문에 40과 50이 아닌 30과 40이 나온다. 그래서 우선순위 큐를 사용해야 최솟값을 구할 수 있는 것이다.
turn2
a + b -> 50 + 70 = 120
sum -> 30 + 70 + 120 = 220
큐에 120밖에 없으므로 종료
답: 220