最大公约数 (数学+离散化)

题目大意:
给定 n ( n ≤ 3 e 5 ) n(n\le 3e5) n(n3e5) 个正整数, a 1 , a 2 , … , a n ( a i ≤ 1.5 e 7 ) a_1,a_2,…,a_n(a_i\le 1.5e7) a1,a2,,an(ai1.5e7),求最少删去几个数,使得删去后这些数的最大公约数比原先的所有数的最大公约数大。

题目分析:
我们可以先通过把每个数除去这 n n n 个数的 g c d gcd gcd 来把他们的公因子剔除,我们再对处理后的数离散化一下,然后我们筛出 m a x a i \sqrt{max_{a_i}} maxai 以内的质数,用一个桶记录一下这些质数是多少个 a i a_i ai 因子,最后找出桶中的最大值 m a x x maxx maxx
如果 m a x x = 0 maxx=0 maxx=0 表示全是 1 1 1 他们的 g c d ≡ 1 gcd\equiv 1 gcd1 无法通过删数减少其最大公约数,此时无解就输出 − 1 -1 1 ,其余情况就是有解情况,当我们把 n − m a x x n-maxx nmaxx 个数字剔除后我们剩余数字的 g c d gcd gcd 就会增大,增大的值就是桶中数字为 m a x x maxx maxx 对应的那个质数
还有一个小细节,如果 a i a_i ai 是质数且 a i > m a x a i a_i>\sqrt{max_{a_i}} ai>maxai 我们应该将这个没筛到过的质数加入质数表中,避免遗漏

具体细节见代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int read()
{
	int res = 0,flag = 1;
	char ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch == '-') flag = -1;
		ch = getchar();
	}
	while(ch>='0' && ch<='9')
	{
		res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
		ch = getchar();
	}
	return res*flag;
}
const int maxn = 1e6+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
struct node{
	int val,cnt;
}nod[maxn];
int n,a[maxn],cnt,pri[maxn],gcdd,num,ans[maxn];
bool vis[maxn];
void get_prime(int n)
{
	for(int i = 2;i <= n;i++)
	{
		if(!vis[i]) pri[++cnt] = i;
		for(int j = 1;j <= cnt && i*pri[j] <= n;j++)
		{
			vis[i*pri[j]] = true;
			if(i%pri[j] == 0) break;
		}
	}
}
int main()
{
	n = read();
	int maxx = 0;
	for(int i = 1;i <= n;i++)
	{
		a[i] = read();
		maxx = max(maxx,a[i]);
		gcdd = i==1 ? a[i] : __gcd(gcdd,a[i]);
	}
	get_prime(sqrt(maxx/gcdd));
	sort(a+1,a+n+1);
	for(int i = 1;i <= n;i++)
		if(a[i] != a[i-1])
		{
			nod[++num].val = a[i]/gcdd;
			nod[num].cnt = 1;
		}
		else nod[num].cnt++;
	for(int i = 1;i <= num;i++)
	{
		bool flag = true;
		for(int j = 1;j <= cnt;j++)
			if(nod[i].val%pri[j] == 0)
				ans[j] += nod[i].cnt,flag = false;
		if(flag && nod[i].val != 1)
		{
			pri[++cnt] = nod[i].val;
			ans[cnt] += nod[i].cnt;
		}
	}
	maxx = *max_element(ans+1,ans+cnt+1);
	if(!maxx) puts("-1");
	else printf("%d\n",n-maxx);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值