Algorithm/Algorithm 문제

백준_1715 카드 정렬하기 (그리디)

kjyyjk 2024. 1. 28. 16:58

 

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

public class BJ_1715_카드정렬하기 {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());

        Queue<Integer> priorityQ = new PriorityQueue<>(); //기본은 오름차순

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

        int result = 0;

        while(priorityQ.size() != 1) {
            int temp = priorityQ.poll() + priorityQ.poll();
            result += temp;
            priorityQ.add(temp);
        }

        System.out.println(new StringBuilder().append(result));
    }

}
 

1715번: 카드 정렬하기

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

www.acmicpc.net