cf #446(div2) C

C. Pride

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the greatest common divisor.

What is the minimum number of operations you need to make all of the elements equal to 1?

Input

The first line of the input contains one integer n (1 ≤ n ≤ 2000) — the number of elements in the array.

The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array.

Output

Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1.

Examples

Input

Copy

5
2 2 3 4 6

Output

Copy

5

Input

Copy

4
2 4 6 8

Output

Copy

-1

Input

Copy

3
2 6 9

Output

Copy

4

Note

In the first sample you can turn all numbers to 1 using the following 5 moves:

  • [2, 2, 3, 4, 6].
  • [2, 1, 3, 4, 6]
  • [2, 1, 3, 1, 6]
  • [2, 1, 1, 1, 6]
  • [1, 1, 1, 1, 6]
  • [1, 1, 1, 1, 1]

We can prove that in this case it is not possible to make all numbers one using less than 5 moves.

题目链接:http://codeforces.com/contest/892/problem/C

题意:有n个数,通过求相邻数之间的gcd,并将其中的一个数改成gcd,求最少几次操作之后可以将n个数都修改成1.数据范围小,可以通过暴力选找将一个数变成1的最小次数,然后将n-1+最小次数即可。

#include
#include
#include
#include
#define inf 0x3f3f3f3f
using namespace std;

const int maxn = 2005;
int a[maxn];

int gcd(int x, int y)
{
    return y==0? x : gcd(y, x%y);
}

int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        for(int i = 0; i < n; i++)
            scanf("%d", a+i);
        int sum = 0;
        for(int i = 0 ; i < n; i++)
            if(a[i] == 1)
                sum ++;
        if(sum)
        {
            printf("%d\n", n-sum);
            continue;
        }
        int ans = inf;
        for(int i = 0; i < n; i++)
        {
            int t = a[i];
            for(int  j = i+1; j < n; j++)
            {
                t = gcd(t, a[j]);
                if(t == 1)
                    ans = min(ans, j-i);
            }
        }
        if(ans == inf) 
            puts("-1");
        else 
            printf("%d\n", ans+n-1);
    }
    
}

 

你可能感兴趣的:(codeforces)