Codeforces Round #827 (Div. 4) D. Coprime 解题报告

原题链接:

Problem - D - Codeforces

题目描述:

Given an array of nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000). Find the maximum value of i+ji+j such that aiai and ajaj are coprime,†† or −1−1 if no such ii, jj exist.

For example consider the array [1,3,5,2,4,7,7][1,3,5,2,4,7,7]. The maximum value of i+ji+j that can be obtained is 5+75+7, since a5=4a5=4 and a7=7a7=7 are coprime.

†† Two integers pp and qq are coprime if the only positive integer that is a divisor of both of them is 11 (that is, their greatest common divisor is 11).

Input

The input consists of multiple test cases. The first line contains an integer tt (1≤t≤101≤t≤10) — the number of test cases. The description of the test cases follows.

The first line of each test case contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the array.

The following line contains nn space-separated positive integers a1a1, a2a2,..., anan (1≤ai≤10001≤ai≤1000) — the elements of the array.

It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.

Output

For each test case, output a single integer  — the maximum value of i+ji+j such that ii and jj satisfy the condition that aiai and ajaj are coprime, or output −1−1 in case no ii, jj satisfy the condition.

题目大意:

给定一个长度为n的正整数数组,找出两个互质数ai和aj,问最大可获得的i+j为多少。如果没有互质数则输出-1。

解题思路:

维护每个数在数组中最后出现的位置。

然后算出1~1000中每个互质数组合,然后去查看数组内有没有这个组合,求最大坐标和。

一开始想到的是,先预处理1~1000中每个互质数组合放入set存放,然后每次输入后去set查看每个与a[i]互质的数是否存在数组当中,实际上这样复杂度开销会更大。

代码(CPP):

#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 2e5 + 10;
const int INF = 0x3fffffff;
int n, a[maxn];
map<int, int> Mp;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cout << fixed;
    cout.precision(18);

    int t;
    cin >> t;
    while(t--)
    {
        Mp.clear();
        cin >> n;
        // 输入并维护每个数在数组中最后出现的位置
        for (int i = 1; i <= n; i++)
        {
            cin >> a[i];
            Mp[a[i]] = i;
        }
        // 算出1~1000中每个互质数组合,然后去查看数组内有没有这个组合,求最大坐标和
        int ans = -1;
        for (int i = 1; i <= 1000; i++)
        {
            for (int j = i; j <= 1000; j++)
            {
                if(__gcd(i, j) == 1 && Mp[i] && Mp[j])
                {
                    ans = max(ans, Mp[i] + Mp[j]);
                }
            }
        }
        cout << ans << endl;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值