Advertisement
ogv

Untitled

ogv
Jan 14th, 2020
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4. private static long solve(int N, int[] a) {
  5. PriorityQueue<Long> pq = new PriorityQueue<>();
  6. for (int ai: a) pq.add((long)ai);
  7.  
  8. long result = 0;
  9. while (!pq.isEmpty()) {
  10. long m1 = pq.poll();
  11. if (pq.isEmpty()) break;
  12. long m2 = pq.poll();
  13.  
  14. long sum = m1 + m2;
  15. result += sum;
  16. pq.add(sum);
  17. }
  18. return result;
  19. }
  20.  
  21. public static long run(Scanner scanner) {
  22. int N = scanner.nextInt();
  23. int[] a = new int[N];
  24. for (int i=0; i < N; i++) a[i] = scanner.nextInt();
  25.  
  26. return solve(N, a);
  27. }
  28.  
  29. public static void main(String[] args) {
  30. try (Scanner scanner = new Scanner(System.in)) {
  31. System.out.println(run(scanner));
  32. }
  33. Tests.run();
  34. }
  35. }
  36.  
  37. class Tests {
  38. public static void run() {
  39. testCase("4\n" +
  40. "10 20 30 40", 190);
  41. testCase("5\n" +
  42. "10 10 10 10 10", 120);
  43. testCase("3\n" +
  44. "1000000000 1000000000 1000000000", 5000000000L);
  45. testCase("6\n" +
  46. "7 6 8 6 1 1", 68);
  47.  
  48. System.out.println("DONE");
  49. }
  50.  
  51. private static void testCase(String input, long expected) {
  52. try (Scanner scanner = new Scanner(input)) {
  53. long result = Main.run(scanner);
  54. if (result != expected) System.out.println("TEST FAILED: was " + result + " expected " + expected + " on input\n" + input);
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement