ICPC East Central NA Regional Contest 2016, Problem F
Bobby Roberts is totally bored in his algorithms class, so he's developed a little solitaire game. He writes down a sequence of positive integers and then begins removing them one at a time. The cost of each removal is equal to the greatest common divisor (gcd) of the two surrounding numbers (wrapping around either end if necessary). For example, if the sequence of numbers was ,
,
,
he could remove the
at a cost of
or he could remove the
at a cost of
. The cost of removing
would be
and the removal of
would cost
. Note that if the
is removed first, the removal of the
afterwards now has a cost of only
.
Bobby keeps a running total of each removal cost. When he ends up with just two numbers remaining he takes their gcd, adds that cost to the running total, and ends the game by removing them both. The object of the game is to remove all of the numbers at the minimum total cost. Unfortunately, he spent so much time in class on this game, he didn't pay attention to several important lectures which would lead him to an algorithm to solve this problem. Since none of you have ever wasted time in your algorithm classes, I'm sure you'll have no problem finding the minimum cost given any sequence of numbers.
Input Specification
Input contains multiple test cases. Each test case consists of a single line starting with an integer which indicates the number of values in the sequence
. This is followed by
positive integers which make up the sequence of values in the game. All of these integers will be
. Input terminates with a line containing a single
0
. There are at most 100 test cases.
Output Specification
For each test case, display the minimum cost of removing all of the numbers.
Sample Input
4 2 3 4 5
5 14 2 4 6 8
0
Sample Output
3
8
Comments