알고리즘

백준 15903번 카드 합체 놀이 (JAVA)

박카스마시며코딩 2022. 4. 2. 17:12

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

 

15903번: 카드 합체 놀이

첫 번째 줄에 카드의 개수를 나타내는 수 n(2 ≤ n ≤ 1,000)과 카드 합체를 몇 번 하는지를 나타내는 수 m(0 ≤ m ≤ 15×n)이 주어진다. 두 번째 줄에 맨 처음 카드의 상태를 나타내는 n개의 자연수 a1,

www.acmicpc.net

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

우선순위 큐를 통해 가장 작은 두개를 찾고 이를 더하고 더한 값을 다시 우선순위 큐에 넣었습니다.

마지막으로 우선순위 큐가 빌때까지 poll하면서 모든 값을 더해주었습니다.

 

package BOJ.ETC;

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

public class BOJ_15903 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine()," ");
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(st.nextToken());
        int m = stoi.apply(st.nextToken());
        PriorityQueue<Long> q = new PriorityQueue();
        st = new StringTokenizer(br.readLine()," ");
        for(int i = 0 ; i < n ; i++){
            long num = stoi.apply(st.nextToken());
            q.offer(num);
        }
        for(int i = 0 ; i < m ; i++){
            long a = q.poll();
            long b = q.poll();
            long num = a+b;
            q.offer(num);
            q.offer(num);
        }
        long result = 0;
        while(!q.isEmpty()){
            result += q.poll();
        }
        System.out.println(result);
    }
}