题意:有n个数,每次取两个相邻的数字x和y把其中的一个值x或者y改变成gcd(x,y),求把这所有的n个数都变成1的最少次数。
思路:很明显的一点是,如果这n个数中存在一个1的话,那么我们只需n-1次就可以把所有的n个数都变成1啦,所以这道题目就可以转变为求出使得n个数中至少存在一个1的最小步骤。
注意要特判有1的情况…
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int gcd(int x, int y)
{
if (y == 0)return x;
return gcd(y, x%y);
}
int main()
{
int n, num[2005];
cin >> n;
int i, j, cnt = 0;
for (i = 1; i <= n; i++) {
cin >> num[i];
if (num[i] == 1)cnt++;//特判含有1的情况
}
if (cnt) {
cout << n - cnt << endl; return 0;
}
else if (n == 1) {//根据某题解,22到31行其实都是不需要的...也确实如此
cout << -1 << endl; return 0;
}
int _gcd = gcd(num[1], num[2]);
for (i = 3; i <= n; i++) {
_gcd = gcd(_gcd, num[i]);
}
if (_gcd > 1) {
cout << -1 << endl; return 0;
}
int ans = 1 << 30;
for (int i = 1; i <= n; i++) {
int x = num[i];
for (int j = i + 1; j <= n; j++) {
x = gcd(x, num[j]);//枚举每个区间,看看哪个最小的区间能满足操作完毕以后gcd为1;对于一个区间的头尾,如果他的头尾两数gcd为1,
//那么我们一定可以用(区间中数的个数-1)次操作使其中一个变成1
if (x == 1) {
ans = min(ans, j - i);
}
}
}
if (ans == 1<<30) cout << -1 << endl;
else cout << ans + n - 1 << endl;
/*for(i=1;i<n;i++)
for (j = 1; j + i <= n; j++) {
if (gcd(num[j], num[j + i]) == 1) {
minn = i; cout << n - 1 + i << endl; return 0;
}
}
cout << -1 << endl;*/
return 0;
}