코딩테스트

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

코드 죄수 2022. 8. 31. 16:28

알고리즘 

가장 작은 수를 출력 시키기 위해서는 가장 작은수 끼리 더하면 된다.

입력 받은 카드들을 우선순위 큐에 저장하고

가장 작은수 부터 꺼내면서 더하고 다시 큐에 넣는 것을 반복한다.

값이 하나 이하로 남았으면 반복을 종료한다.

 

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

public class Main {
	
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
        int num = Integer.parseInt(br.readLine());
        int result = 0;
        
        
        for (int i = 0; i < num; i++) {	// 카드 수만큼 입력 받기 
            pq.add(Integer.parseInt(br.readLine()));
        }
 
        while ((pq.size() > 1)) {	// 큐에 값이 하나 남을 때 까지 반복
            int addnum = pq.poll() + pq.poll();	// 수 2개 더하기
            pq.add(addnum);	// 더한 값 다시 큐에 입력
            result += addnum;	// 더한값을 계속 누적 시킴
        }
        
        System.out.println(result);	//누적된 값을 출력
	}
}