原题链接:
题目描述:
You are given an array aa consisting of nn integers a1,a2,…,ana1,a2,…,an. Friends asked you to make the greatest common divisor (GCD) of all numbers in the array equal to 11. In one operation, you can do the following:
- Select an arbitrary index in the array 1≤i≤n1≤i≤n;
- Make ai=gcd(ai,i)ai=gcd(ai,i), where gcd(x,y)gcd(x,y) denotes the GCD of integers xx and yy. The cost of such an operation is n−i+1n−i+1.
You need to find the minimum total cost of operations we need to perform so that the GCD of the all array numbers becomes equal to 11.
Input
Each test consists of multiple test cases. The first line contains an integer tt (1≤t≤50001≤t≤5000) — the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer nn (1≤n≤201≤n≤20) — the length of the array.
The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — the elements of the array.
Output
For each test case, output a single integer — the minimum total cost of operations that will need to be performed so that the GCD of all numbers in the array becomes equal to 11.
We can show that it's always possible to do so.
题目大意:
给定一个长度为n的正整数数组,每次操作选择一个i,使得ai=gcd(ai,i),操作的代价为n-i+1,请问要使得整个数组gcd为1最小要花费多少代价。
解题思路:
两个相邻的自然数的gcd = 1,因此我们先判断数组原来是不是gcd = 1,如果不是就改最后一位,花费是1;或者看倒数第二位,花费是2;改完还不够就是把后两个都改了, 花费是1 + 2 = 3。
代码(CPP):
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e2 + 10;
const int INF = 0x3fffffff;
int n, a[maxn];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout << fixed;
cout.precision(18);
int t;
cin >> t;
while(t--)
{
cin >> n;
int Min = 3, g;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
if(i < 2)
g = a[i];
else
g = __gcd(g, a[i]);
}
if(g == 1)
{
cout << "0" << endl;
continue;
}
for (int i = n; i >= n - 1; i--)
{
if(__gcd(g, i) == 1)
Min = min(Min, n - i + 1);
}
cout << Min << endl;
}
return 0;
}