알고리즘/BOJ

[BOJ] 1715. 카드 정렬하기

재담 2022. 4. 4. 01:09

문제 원본 : https://www.acmicpc.net/problem/1715

 

1715번: 카드 정렬하기

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

www.acmicpc.net

import java.io.*;
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int n = Integer.parseInt(br.readLine());
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

        for (int i = 0; i < n; ++i) {
            priorityQueue.add(Integer.parseInt(br.readLine()));
        }

        int ans = 0;
        while (priorityQueue.size() > 1) {
            int next = priorityQueue.poll() + priorityQueue.poll();
            ans += next;
            priorityQueue.add(next);
        }

        bw.write(String.valueOf(ans));

        bw.close();
        br.close();
    }
}
  • 그리디 알고리즘을 이용한 문제
  • 우선순위 큐를 이용해 제일 위에 있는 2개를 더하고 그 값을 다시 우선순위 큐에 넣는 작업을 반복하면 풀린다.