Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Main {
- private static long solve(int N, int[] a) {
- PriorityQueue<Long> pq = new PriorityQueue<>();
- for (int ai: a) pq.add((long)ai);
- long result = 0;
- while (!pq.isEmpty()) {
- long m1 = pq.poll();
- if (pq.isEmpty()) break;
- long m2 = pq.poll();
- long sum = m1 + m2;
- result += sum;
- pq.add(sum);
- }
- return result;
- }
- public static long run(Scanner scanner) {
- int N = scanner.nextInt();
- int[] a = new int[N];
- for (int i=0; i < N; i++) a[i] = scanner.nextInt();
- return solve(N, a);
- }
- public static void main(String[] args) {
- try (Scanner scanner = new Scanner(System.in)) {
- System.out.println(run(scanner));
- }
- Tests.run();
- }
- }
- class Tests {
- public static void run() {
- testCase("4\n" +
- "10 20 30 40", 190);
- testCase("5\n" +
- "10 10 10 10 10", 120);
- testCase("3\n" +
- "1000000000 1000000000 1000000000", 5000000000L);
- testCase("6\n" +
- "7 6 8 6 1 1", 68);
- System.out.println("DONE");
- }
- private static void testCase(String input, long expected) {
- try (Scanner scanner = new Scanner(input)) {
- long result = Main.run(scanner);
- if (result != expected) System.out.println("TEST FAILED: was " + result + " expected " + expected + " on input\n" + input);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement