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?
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(x,y) 就这个意思 然后问你最后能不能变成一个全部都是一的数组 如果不能 就输出-1 如果可以就输出 最少步数
我用的方法很暴力 就是暴力O(n^2)枚举任意区间gcd 找到最短的到1的路劲 然后就好了 对没错
C++ 写的版本
#include <iostream>
using namespace std;
const static int N = 3000;
int gcd(int a, int b)
{
if(!b)return a;
else return gcd(b , a % b);
}
int main()
{
int array[N] , n , m;
while ( cin >> n && n) {
bool flag = false;
int cnt = 0;
for (int i = 0; i < n; i ++) {
cin >> array[i];
if(array[i] == 1) {
flag = true;
} else cnt ++;
}
if(flag) {
cout << cnt << endl;return 0;
}
int minn , minn_time = 0x7fffffff;
for (int i = 0; i < n; i ++) {
int p = array[i + 1];
for (int j = i + 1; j < n; j ++) {
if(j == i + 1) p = gcd(p , array[i]);
else
p = gcd(p , array[j]);
if(p == 1) {
// printf("The gcd from %d to %d is 1 \n",i , j);
minn_time = min(minn_time , j - i);
flag = true;break;
}
}
}
//printf("minn_time == %d\n",minn_time);
if(minn_time == 0x7fffffff) puts("-1");
else cout << minn_time + cnt - 1<< endl;
}
}
值得一提的是这道题的python版本如果交PyPy版本能过 但是python3.6 会TLE 果然Py大法好
def gcd(a, b):
if b == 0:
return a
return gcd(b , a%b)
nums = int(input())
array = input().split()
flag = False
cnt = 0
for obj in array:
if int(obj) == 1:
flag = True
else:
cnt += 1
if cnt != len(array):
print(cnt)
else :
minn_time = 0x7fffffff
for i in range(0 , len(array)):
if i != len(array) - 1:
p = int(array[i + 1])
else :
p = int(array[i])
for j in range(i + 1 , len(array)):
# if i == len(array) - 1:
# print("we are here ")
if j == i + 1:
p = gcd(p , int(array[i]))
else :
p = gcd(p , int(array[j]))
if p == 1:
# print("we are here")
minn_time = min(minn_time , j - i)
flag = True
# break
if minn_time == 0x7fffffff :
print("-1")
else :
print(minn_time + cnt - 1)