Almost All Divisors CodeForces - 1165D

原题链接
考察:思维
错误思路:
  每个数求lcm,检查lcm的因子是否在d数组内. TLE
思路:
  如果存在的话,最后答案一定是res = d[n]*d[1](排序后),我们检查res的因子,最后比较个数即可(一定要比个数).

Code

#include <iostream> 
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 310;
int n,d[N];
bool get(LL x)
{
	int idx = lower_bound(d+1,d+n+1,x)-d;
	if(d[idx]==x) return 1;
	return 0;
}
bool check(LL x)
{
	int cnt = 0;
	for(int i=2;i<=x/i;i++)
	{
		if(x%i==0)
		{
			if(!get(i)) return 0;
			cnt++;//存在d数组多了一些无关数字的情况 
			if(x/i==i) continue;
			if(!get(x/i)) return 0;
			cnt++;
		}
	}
	return cnt==n;
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		for(int i=1;i<=n;i++) scanf("%d",&d[i]);
		sort(d+1,d+n+1);
		LL res = (LL)d[1]*d[n];
		if(check(res)) printf("%lld\n",res);
		else puts("-1");
	}
	return 0;
}
posted @ 2021-06-30 10:43  acmloser  阅读(32)  评论(0编辑  收藏  举报