1. 程式人生 > >codeforces511 div2C/div1A enlarge gcd 數論+思維

codeforces511 div2C/div1A enlarge gcd 數論+思維

題意:

給你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; }