跳到正文

题解

CF1742D 题解

qwertim约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
CF1742D

版本

  1. v1当前

题目传送门

思路 1

倒着找 ii 和 jj。 时间复杂度为 O(n2)O(n^2) ,肯定超时。

思路 2

仔细看题中的数据范围:1≤ai≤10001 \le a_i \le 1000。

于是,我们可以用一个桶记录 11 至 10001000 中的所有互质的数对,再枚举桶里面所有的数对,判断数组里是否存在这个数对。如存在,就刷新答案。

注:__gcd(a,b)代表 aa 和 bb 的最大公约数。

最终 code

C++
#include<bits/stdc++.h>
#define fo(i,l,r) for(int i=l;i<=r;i++)
using namespace std;
int t,n,a[200005];
map<pair<int,int>,bool>m;//存互质数对的桶
void gz(){//找出1~1000中所有的互质数对
	fo(i,1,1000)
		fo(j,i,1000)
			if(__gcd(i,j)==1)m[make_pair(i,j)]=1;
}
int main(){
	cin>>t;
    gz();
	while(t--){
		scanf("%d",&n);
		int ans=-1;
		map<int,int>mp;//存下标的桶
		fo(i,1,n)scanf("%d",&a[i]),mp[a[i]]=i;//记录下标
		for(auto it:m)//遍历m
			if(mp[it.first.first]>0&&mp[it.first.second]>0)
            	ans=max(ans,mp[it.first.first]+mp[it.first.second]);//刷新答案
		printf("%d\n",ans);//输出
	}
	return 0;
}
原文