자료구조 & 알고리즘/BOJ

[java] 백준 1715번 문제(카드 정렬하기)

seungwook_TIL 2025. 4. 7. 11:52

원본 링크 : https://www.acmicpc.net/problem/1715


문제설명

 

소스코드

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

public class Boj_1715
{
    public static void main(String[] args) throws IOException
    {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());
        for (int i = 0; i < n; ++i) pq.offer(Integer.parseInt(br.readLine()));

        int totalSum = 0;
        while (pq.size() > 1)
        {
            int n1 = pq.poll();
            int n2 = pq.poll();
            pq.offer(n1 + n2);
            totalSum += (n1 + n2);
        }
        System.out.print(totalSum);
    }
}

 

설명

  • 우선순위 큐를 이용해서 값을 더한 후 다시 삽입했을 때에도 정렬이 되도록 유지한다.