알고리즘

백준 1715번 카드 정렬하기 (JAVA)

박카스마시며코딩 2022. 3. 16. 16:01

https://www.acmicpc.net/problem/1715

 

1715번: 카드 정렬하기

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

www.acmicpc.net

 

저는 해당 문제를 우선순위 큐를 이용해 문제를 해결하였습니다.

우선 순위 큐를 통해 작은 값 두개를 꺼내서 더해주고 이 값을 result에 더하고 다시 큐에 넣었습니다.

위의 과정을 큐의 사이즈가 1이 될때까지 하였습니다.

 

package BOJ.ETC;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_1715 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(br.readLine());
        Queue<Integer> q = new PriorityQueue<>();
        for(int i = 0 ; i < n ; i++){
            int num = stoi.apply(br.readLine());
            q.offer(num);
        }
        long result = 0;
        while(q.size() > 1){
            int num1 = q.poll();
            int num2 = q.poll();
            q.offer(num1 + num2);
            result += (num1+num2);
        }
        System.out.println(result);
    }
}