# BZOJ 2301 - Problem b（莫比乌斯反演+容斥）

【题意】

【思路】

$s1=\sum _{x=1}^{b}\sum _{y=1}^{d}\left[gcd\left(x,y\right)=k\right]$
$s2=\sum _{x=1}^{a-1}\sum _{y=1}^{d}\left[gcd\left(x,y\right)=k\right]$
$s3=\sum _{x=1}^{c-1}\sum _{y=1}^{b}\left[gcd\left(x,y\right)=k\right]$
$s4=\sum _{x=1}^{a-1}\sum _{y=1}^{c-1}\left[gcd\left(x,y\right)=k\right]$

$ans=s1-s2-s3+s4$

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn=50005;

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]+mu[i];
}

ll solve(int a,int b){
if(a>b) swap(a,b);
ll ans=0;
for(int L=1,R;L<=a;L=R+1){
R=min(a/(a/L),b/(b/L));
ans+=(sum[R]-sum[L-1])*(a/L)*(b/L);
}
return ans;
}

int main(){
get_mu(maxn-1);
int T;
scanf("%d",&T);
while(T--){
int a,b,c,d,k;
scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
ll s1=solve(b/k,d/k);
ll s2=solve((a-1)/k,d/k);
ll s3=solve((c-1)/k,b/k);
ll s4=solve((a-1)/k,(c-1)/k);
ll ans=s1-s2-s3+s4;
printf("%lld\n",ans);
}
return 0;
}

posted @ 2018-08-30 16:16  不想吃WA的咸鱼  阅读(25)  评论(0编辑  收藏