codeforces511 div2C/div1A enlarge gcd 数论+思维

版权声明:若转载请附上原博客链接,谢谢! https://blog.csdn.net/Link_Ray/article/details/83068420

题意:

给你n个数,需要删除几个数,使得剩余数的gcd大于初始数的gcd,问最少需要删除多少个数。

题解:

所有数的gcd是跟每个数的质因子有关的,此题只需算出删除数的个数,不需要计算删除数后的gcd。首先,算出所有数的gcd,然后一次枚举每一个数,先将这个数除以gcd,之后在枚举质数p,算每个数所贡献的质数cnt[prime]++。答案就是n-max{ cnt[prime] }。

这个复杂度如果直接枚举全部质数的话复杂度太高,可以发现2,4,6,8…都可以归于一个质数2,因为我们只需要比初始gcd大,所以只需计算对2的贡献即可。


#include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5+5;
const int N = 15000000;
int gcd(int a,int b) {
    return b == 0 ? a : gcd(b, a%b);
}
int a[maxn];
int check[N+5];
int prime[N+5],phi[N+5];
int tot;
void phi_table() {
    memset(check, 0 ,sizeof check);
    for(int i = 2; i <= N; ++i) {
        if(!check[i]) 
            for(int j = i; j <= N; j+= i)
                check[j] = i;
    }
}
int cnt[N+5];
int main() {
    phi_table();
    // cout << tot << endl;
    // cout << -1 << endl;
    int n;
    scanf("%d", &n);
    int GCD = 0;
    for(int i = 0; i < n; ++i) {
        scanf("%d", &a[i]);
        GCD = gcd(GCD, a[i]);
    }
    for(int i = 0; i < n; ++i) {
        int t = a[i]/GCD;
        for(int x = check[t]; x > 1;) {
            cnt[x]++; // 含有质因子x的a[i]个数
            while(t%x == 0) t /= x;
            x = check[t];
        }
    }
    int ans = 0;
    for(int i = 0; i <= N; ++i) {
        if(cnt[i] > ans)
            ans = max(ans,cnt[i]);
    }
    ans = n-ans;
    if(ans == n)
        puts("-1");
    else {
        cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Link_Ray/article/details/83068420