CF#446 Pride(水暴力)

来源:互联网 发布:80端口改变如何恢复 编辑:程序博客网 时间:2024/04/29 02:22

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 xand 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
52 2 3 4 6
output
5
input
42 4 6 8
output
-1
input
32 6 9
output
4
Note

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


题意:一列数,每次可以取两个相邻数并且把其中一个变成最大公约数,问多少次可以使数列全为1,不能全为1输出-1.

思路:因为每次只能变化一个数,所以如果初始数列就有m个1,那么就只需操作n-m次,如果没有我们可以暴力求解每个数去和相邻数运算多少次可以出现1,然后用那个1去和其他元素运算即可.

#include<cstdio>#include<iostream>#include<algorithm>#include<queue>#include<stack>#include<cstring>#include<string>#include<vector>#include<cmath> #include<map>#define mem(a,b) memset(a,b,sizeof(a))using namespace std;typedef long long ll;const int maxn = 1e6+5;const int ff = 0x3f3f3f3f;int n;int a[5200];int gcd(int x,int y){if(x< y)x = x^y,y = x^y,x = x^y;return x%y == 0?y:gcd(y,x%y);}int main(){cin>>n;int cnt = 0;for(int i = 1;i<= n;i++){scanf("%d",&a[i]);if(a[i] == 1)cnt++;}if(cnt){cout<<n-cnt<<endl;return 0;}int mint = ff;for(int i = 1;i<= n;i++){int x = a[i];cnt = 0;for(int j = i+1;j<= n;j++){cnt++;x = gcd(x,a[j]);if(x == 1)break;}if(x == 1)mint = min(mint,cnt);}if(mint == ff)cout<<-1<<endl;elsecout<<mint+n-1<<endl;return 0;}