HDU 1695 - GCD(莫比乌斯反演)

题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1695

【题意】
给你 a , b , c , d , k 五个值 a = c = 1 x [ 1 , b ] y [ 1 , d ] 让你求有多少对这样的 x , y 满足 g c d x , y ) = k ( x , y ) ( y , x ) 被看作是相同的整数对

【思路】
根据莫比乌斯反演可知在 x [ 1 , b ] y [ 1 , d ] 中, g c d ( x , y ) == k 的个数为

x = 1 m i n ( b , d ) μ ( x ) b x d x

这个算出来的结果是有重复的,也就是 ( x , y ) ( y , x ) 都被算过一次,只要减去 x [ 1 , m i n ( b , d ) ] y [ 1 , m i n ( b , d ) ] 中, g c d ( x , y ) == k 答案的一半就可以了

这里写图片描述

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=100050;

bool vis[maxn];
int prim[maxn];
int mu[maxn];
ll sum[maxn];
int cnt;

void get_mu(int n){
    mu[1]=1;
    for(int i=2;i<=n;i++){
        if(!vis[i]){
            prim[++cnt]=i;
            mu[i]=-1;
        }
        for(int j=1;j<=cnt && prim[j]*i<=n;j++){
            vis[prim[j]*i]=1;
            if(i%prim[j]==0) break;
            else mu[i*prim[j]]=-mu[i];
        }
    }
    for(int i=1;i<maxn;++i) sum[i]=sum[i-1]+(ll)mu[i];
}

ll solve(int a,int b){
    ll x=0,y=0;
    for(int L=1,R;L<=a;L=R+1){
        R=min(a/(a/L),b/(b/L));
        x+=(sum[R]-sum[L-1])*(ll)(a/L)*(ll)(b/L);
    }

    for(int L=1,R;L<=a;L=R+1){
        R=a/(a/L);
        y+=(sum[R]-sum[L-1])*(ll)(a/L)*(ll)(a/L);
    }
    return x-y/2;
}

int main(){
    get_mu(maxn-1);
    int T;
    scanf("%d",&T);
    for(int kase=1;kase<=T;++kase){
        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",kase);
            continue;
        }
        if(b>d) swap(b,d);
        ll ans=solve(b/k,d/k);
        printf("Case %d: %lld\n",kase,ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiao_k666/article/details/82222321