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
5
2 2 3 4 6
output
5
input
4
2 4 6 8
output
-1
input
3
2 6 9
output
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.
题意:你可以用相邻两个数的gcd替换两个数之中的一个,问你把所有数全部变为1,需要的最少次数。如果不能完成输出-1
思路:
如果序列中有1,就是n-count(1),没有1的话,就是从左往右的暴力,把替换的数全部替换为右边的一个。每一位都存储到这位gcd的所有可能。最后在枚举所有可能里面,数值为1,且次数最小的哪个,然后结果就是n-1 + min
比赛是忘记判断1的个数,最后5分钟的时候被hack了,哎呀,好气呀!!!
代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int INF = 0x3f3f3f3f;
const int MAX = 2020;
int a[MAX],N;
multiset<int> st;
vector<P> V[MAX];//存储到这一位的所有可能结果
//first 代表gcd,second代表到得到这个数的次数
int solve(){
if(st.count(1) != 0) return N-st.count(1);
for(int i=1;i<=N;++i){
for(int j=0;j<V[i-1].size();++j){
P p = V[i-1][j];
p.first = __gcd(p.first,a[i]);
p.second++;
V[i].push_back(p);
}
V[i].push_back(P{a[i],0});
}
int Min = INF;
for(int i=1;i<=N;++i){
for(int j=0;j<V[i].size();++j){
P p = V[i][j];
if(p.first == 1)
Min = min(Min,p.second);
}
}
if(Min == INF) return -1;
else return Min + (N-1);
}
int main(void){
scanf("%d",&N);
for(int i=1;i<=N;++i){
scanf("%d",&a[i]);
st.insert(a[i]);
}
printf("%d\n",solve());
return 0;
}