Tying All the Cards
Time limit5sMemory limit768 MB
Tie all N cards into one connected set where each tie costs the larger number modulo the smaller, with minimum total cost.
- Level
Hard8 of 10
- Topics
- Minimum spanning tree, Number theory, Union-find
- Solved
- No attempts yet
Problem
Daniel has a bag of candy and cards. Each card has one positive integer written on it.
While eating his candy, Daniel thought of a game. He can tie together two cards labelled and , and each tie forces him to eat pieces of candy, where is the remainder of divided by .
Daniel wants to tie the cards so that lifting any one card lifts all the others with it. A single card can be tied directly to any number of other cards. Daniel watches his figure, so he does not want to eat much.
Compute the smallest number of candy pieces he must eat to connect all the cards.
Input
The first line contains the positive integer . ()
Each of the next lines contains one positive integer written on a card. ()
Output
Print on the first line the smallest number of candy pieces needed to connect all the cards.
Hint
In the first example Daniel ties the first card to the second and eats 0 candy, ties the second card to the third and eats 0 candy, then ties the first card to the fourth and eats 1 candy. One piece of candy connects all four cards.