import java.io.*;
import java.util.*;
public class Main {
public static int connectSticks(int[] sticks) {
//add all sticks in a priority queue
Queue<Integer> q = new PriorityQueue<>();
for(int val : sticks)
q.add(val);
int ans = 0;
while(q.size()!=1){
int cost = q.remove()+q.remove();
ans += cost;
q.add(cost);
}
return ans;
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] sticks = new int[n];
for (int i = 0; i < sticks.length; i++) {
sticks[i] = scn.nextInt();
}
System.out.println(connectSticks(sticks));
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter