백준/1 - 5000
[백준] 1715번 : 카드 정렬하기(JAVA)
lms0806
2021. 10. 29. 02:15
728x90
https://www.acmicpc.net/problem/1715
1715번: 카드 정렬하기
정렬된 두 묶음의 숫자 카드가 있다고 하자. 각 묶음의 카드의 수를 A, B라 하면 보통 두 묶음을 합쳐서 하나로 만드는 데에는 A+B 번의 비교를 해야 한다. 이를테면, 20장의 숫자 카드 묶음과 30장
www.acmicpc.net
풀이
우선순위 큐를 이용하여 가장 작은 수 더한값을 answer에 더해주고 더한값을 우선순위큐에 넣는 방식으로 pq의 크기가 1이 될때까지 반복하시면 됩니다.
소스코드
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<>();
int n = Integer.parseInt(br.readLine());
while(n --> 0) {
pq.add(Integer.parseInt(br.readLine()));
}
long answer = 0;
while(pq.size() != 1) {
int num = pq.poll() + pq.poll();
answer += num;
pq.add(num);
}
System.out.print(answer);
}
}
728x90