标签:include define turn typedef tar this follow com numbers
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:
We can prove that in this case it is not possible to make all numbers one using less than 5 moves.
像dp的东西,每次处理前i项,第i项要与第i-1项不互质的话,就需要将第i-1项赋值为其gcd然后往前重复操作至互质,f[i]即为从i点开始向前的最少步数
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define inf 2147483647 const ll INF = 0x3f3f3f3f3f3f3f3fll; #define ri register int template <class T> inline T min(T a, T b, T c) { return min(min(a, b), c); } template <class T> inline T max(T a, T b, T c) { return max(max(a, b), c); } template <class T> inline T min(T a, T b, T c, T d) { return min(min(a, b), min(c, d)); } template <class T> inline T max(T a, T b, T c, T d) { return max(max(a, b), max(c, d)); } #define scanf1(x) scanf("%d", &x) #define scanf2(x, y) scanf("%d%d", &x, &y) #define scanf3(x, y, z) scanf("%d%d%d", &x, &y, &z) #define scanf4(x, y, z, X) scanf("%d%d%d%d", &x, &y, &z, &X) #define pi acos(-1) #define me(x, y) memset(x, y, sizeof(x)); #define For(i, a, b) for (int i = a; i <= b; i++) #define FFor(i, a, b) for (int i = a; i >= b; i--) #define bug printf("***********\n"); #define mp make_pair #define pb push_back const int N=3000; // name******************************* int f[N]; int ans=inf; int a[N]; int n; int cnt=0; // function****************************** //*************************************** int main() { // ios::sync_with_stdio(0); // cin.tie(0); // freopen("test.txt", "r", stdin); // freopen("outout.txt","w",stdout); cin>>n; For(i,1,n) { cin>>a[i]; if(a[i]==1)cnt++; } if(cnt!=0) { cout<<n-cnt; return 0; } For(i,2,n) { int j=i-1; bool flag=false; int cnt=0; int t=a[i]; FFor(j,i-1,1) { cnt++; int g=__gcd(a[j],t); if(g!=1) { t=g; } else { flag=true; break; } } if(flag) ans=min(ans,cnt); } if(ans!=inf) { ans+=n-1; cout<<ans; } else cout<<-1; return 0; }
标签:include define turn typedef tar this follow com numbers
原文地址:https://www.cnblogs.com/planche/p/8778454.html