Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

알고리즘 공부방

벡준 14698 전생했더니 슬라임 연구자였던 건에 대하여 (Hard)(JAVA) 본문

알고리즘

벡준 14698 전생했더니 슬라임 연구자였던 건에 대하여 (Hard)(JAVA)

head89 2022. 12. 21. 11:13

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

 

14698번: 전생했더니 슬라임 연구자였던 건에 대하여 (Hard)

각 테스트 케이스마다 슬라임을 끝까지 합성했을 때 청구될 비용의 최솟값을 1, 000, 000, 007로 나눈 나머지를 출력한다. 전기 에너지가 전혀 필요하지 않은 경우엔 1 을 출력한다.

www.acmicpc.net

문제 유형: 그리디, 우선순위 큐

 

 

문제 풀이

입력이 최대 1000000이기에 O(nlogn)풀이로 풀 수 있다.

그렇기에 우선순위 큐를 써 그리디하게 가장 작은 것 두개를 곱하고 다시 넣고,

큐 사이즈가 1이 될때까지 반복한다.

(오버플로우 조심하자..)

 

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


public class Main {

    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int T = Integer.parseInt(br.readLine());

        while (T-->0){
            int n = Integer.parseInt(br.readLine());

            StringTokenizer st = new StringTokenizer(br.readLine());

            PriorityQueue<Long> queue = new PriorityQueue<>();

            for(int i = 0;i<n;i++){
                queue.add(Long.parseLong(st.nextToken()));
            }
            if(n == 1) {
                sb.append(1).append("\n");
                continue;
            }
            long cnt = 1;

            while (queue.size() > 1){
                long c1 = queue.poll();
                long c2 = queue.poll();
                cnt = cnt * ((c1 * c2) % 1000000007) % 1000000007;
                queue.add(c1 * c2);
            }
            sb.append(cnt).append("\n");
        }
        System.out.println(sb);
    }
}