(UVA) Add All - Solution
Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1895
The solution below used a Priority Queue to solve this problem because the best solution is always to sum the two smallest numbers.
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int numNumbers = sc.nextInt();
while (numNumbers != 0) {
Queue<Integer> queue = new PriorityQueue<>();
for (int i = 0; i < numNumbers; i++) {
queue.add(sc.nextInt());
}
int lastSum = queue.poll()+queue.poll();
queue.add(lastSum);
int sumCost = lastSum;
for (int i = 2; i < numNumbers; i++) {
lastSum = queue.poll()+queue.poll();
queue.add(lastSum);
sumCost += lastSum;
}
bw.write(sumCost+"\n");
numNumbers = sc.nextInt();
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
The solution below used a Priority Queue to solve this problem because the best solution is always to sum the two smallest numbers.
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int numNumbers = sc.nextInt();
while (numNumbers != 0) {
Queue<Integer> queue = new PriorityQueue<>();
for (int i = 0; i < numNumbers; i++) {
queue.add(sc.nextInt());
}
int lastSum = queue.poll()+queue.poll();
queue.add(lastSum);
int sumCost = lastSum;
for (int i = 2; i < numNumbers; i++) {
lastSum = queue.poll()+queue.poll();
queue.add(lastSum);
sumCost += lastSum;
}
bw.write(sumCost+"\n");
numNumbers = sc.nextInt();
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment