HDU1695GCD 容斥

原来用莫比乌斯写过这个传送门,发现这个用容斥挺好理解,就是跑的比莫比乌斯慢,莫比乌斯跑了40ms,这个跑了400ms。

估计复杂度是O(n*6*2^6)大约4e7。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+10;
vector<int> p[N];

void getP(){
    for(int i=2; i<=1e5; i++){
        int m=sqrt(i+0.5), t=i;
        for(int j=2; j<=m; j++) if(t%j==0){
        p[i].push_back(j);      while(t%j==0) t/=j; }

        if(t>1) p[i].push_back(t);
    }
}

ll cal(int id, int s, int n){
    ll v=1, cnt=0;
    for(int i=0; i<p[id].size(); i++){
        if((1<<i)&s){
            cnt++; v*=p[id][i];
        }
    }

    v=n/v;
    if(cnt&1) return v;
    else return -v;
}

int main(){
    getP();

    int T, cas=0;
    scanf("%d", &T);
    while(T--){
        int a, b, c, d, k;
        scanf("%d%d%d%d%d", &a, &b, &c, &d, &k);

        if(k==0){
            printf("Case %d: 0\n", ++cas);
            continue;
        }

        b/=k; d/=k;
        if(b>d) swap(b,d);
        ll ans=0;
        for(int i=1; i<=d; i++){
            int t=min(i, b);
            ans+=t;
            for(int j=1; j<1<<(p[i].size()); j++)
                ans-=cal(i, j, t);

        }
        printf("Case %d: %lld\n", ++cas, ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/du_lun/article/details/81674759