N(1~2000)个数,每次操作可以将相邻两数的其中一个变为它们的最大公约数,求将所有数变为1所需的最少操作次数
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define INF 0x3f3f3f3f using namespace std; typedef long long LL; const int maxn = 2e3 + 10; int A[maxn]; int N; int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } int main() { int cnt = 0; scanf("%d", &N); for (int i = 1; i <= N; i++) { scanf("%d", &A[i]); if (A[i] == 1) cnt++; } int ans = N + 1; for (int i = 1; i <= N; i++) { int a = 0; for (int j = i; j <= N; j++) { a = gcd(A[j], a); if (a == 1) { ans = min(ans, j - i + 1); break; } } } if (ans == N + 1) { puts("-1"); } else { if (cnt) ans = N - cnt; else ans = N + ans - 2; printf("%d ", ans); } return 0; }