You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacentelements 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?
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.
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.
5
2 2 3 4 6
5
4
2 4 6 8
-1
3
2 6 9
4
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.
题意:题意很简单,我们可以让相邻的数变成他们的gcd,操作数+1,我们要使得所有元素变成1,能变成输出操作数,反之输出-1
思路:如果存在一个1,那么我们直接输出n-p(1的个数),若所有书gcd!=1 那么肯定无解,其他的我们只要找到一些连续元素的gcd为1的区间就行。
代码:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include<bits/stdc++.h> using namespace std; #define fio ios_base::sync_with_stdio(false),cin.tie(0); #define Pii pair<int,int> #define INF 0x3f3f3f3f #define ll long long const int maxn = 200005; int a[2005]; int main() { fio; int n,p=0; cin>>n; int d=0; for(int i=1; i<=n; i++) { cin>>a[i]; if(a[i]==1) p++; d=__gcd(d,a[i]); } if(d!=1) cout<<-1<<endl; else { if(p) { cout<<n-p<<endl; return 0; } int len=INF; for(int i=1; i<=n; i++) { d=a[i]; for(int j=i+1; j<=n; j++) { d=__gcd(a[j],d); if(d==1) { len=min(len,j-i+1); break; } } } cout<<len-1+n-1<<endl; } }
PS:摸鱼怪的博客分享,欢迎感谢各路大牛的指点~