原题链接:
题目描述:
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;
}