[백준] PS/Java

[백준 1715] 카드 정렬하기 - JAVA

SH3542 2025. 5. 10. 17:40

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

 

숫자가 작은 카드부터 더하는게 최적이다.

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

class Main {

  public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int N = Integer.parseInt(br.readLine());

    PriorityQueue<Integer> q = new PriorityQueue<>();

    for (int i = 0; i < N; i++) {
      q.offer(Integer.parseInt(br.readLine()));
    }

    int ans = 0;
    while (q.size() > 1) {
      int n = q.poll() + q.poll();
      ans += n;
      q.offer(n);
    }
    System.out.println(ans);
  }
}