Codeforces Round #830 (Div. 2) A. Bestie 解题报告

原题链接:

Problem - A - Codeforces

题目描述:

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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值