Codeforces Round #511 (Div. 2) C. Enlarge GCD 【暴力枚举+素数晒法】

版权声明:如需转载,记得标识出处 https://blog.csdn.net/godleaf/article/details/82933457

题目链接:http://codeforces.com/contest/1047/problem/C

题意:删去尽可能少的数,得到一个比原先的gcd大的gcd,如果没有就输出-1,有就输出删除的个数;

思路:

用素数晒法,去枚举大于g(最初的gcd)的数,计数数组中有几个数能被g整除,取个数的最大值;要注意的是,如果只有两个数 1 2,那么可以删除1这个数得到更大的gcd;

#include<bits/stdc++.h>

using namespace std;

const int Maxn = 2e7;

int cnt[Maxn];
bool used[Maxn];

int main (void) 
{
	int n,maxn = 0,tmp,g = -1;
	scanf("%d",&n);
	for (int i = 0; i < n; ++i) {
		scanf("%d",&tmp);
		cnt[tmp]++;
		if(g == -1) g = tmp;
		else g = __gcd (g, tmp);
		maxn = max (tmp, maxn);
	}
	
	int ans = 0;
	for (int i = g+1; i <= maxn; ++i) {
		int ct = 0;
		if(!used[i]) {
			for (int j = i; j <= maxn; j+=i) {
				ct+=cnt[j]; used[j] = 1;
			}
			ans = max (ans, ct);
		}
	}
	int ret = ans ? n-ans : -1;
	printf("%d\n",ret);
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/godleaf/article/details/82933457