Problem 135
Last Stone Weight
Problem
You have a collection of stones with positive weights. Each turn, take the two heaviest stones, with weights x <= y, and smash them together. If x == y, both stones are destroyed. Otherwise the stone of weight x is destroyed and the other stone now weighs y - x. Repeat until at most one stone is left, and print its weight, or 0 if no stones remain. A max-heap (priority queue) makes it easy to take the two heaviest stones each turn.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the weight of the last stone, or 0.
Constraints
1 <= N <= 1000; 1 <= weight <= 1000
Example input
6 2 7 4 1 8 1
Example output
1
Explanation
With 2 7 4 1 8 1: smash 8 and 7 to get 1, leaving 2 4 1 1 1. Smash 4 and 2 to get 2, leaving 2 1 1 1. Smash 2 and 1 to get 1, leaving 1 1 1. Smash 1 and 1, which destroys both, leaving one stone of weight 1.