BZOJ1101
http://www.lydsy.com/JudgeOnline/problem.php?id=1101
求gcd(a,b)=k
a,b中必然包含k的因子
问题等价于a'=a/k,b'=b/k,求有多少对(i,j),其gcd(i,j)=1,1<=i<=a',1<=j<=b'
ans=Σ(i=1,a')Σ(j=1,b')[gcd(i,j)=1]
=Σ(i=1,a')Σ(j=1,b')Σ(d|gcd(i,j))μ(d)
=Σ(i=1,a')Σ(j=1,b')Σ(d|i,d|j)μ(d)
=Σ(d)Σ(i=1,a',d|i)Σ(j=1,b',d|j)μ(d)
=Σ(d)μ(d)*[a'/d]*[b'/d]
这样就有一个线性的做法
复杂度为O(Tn)
70分线性做法
#include<cstdio>
typedef long long ll;
ll ans;
inline int min(int a,int b){
return a<b?a:b;
}
const int N=50011;
bool ip[N];
int pr[N],miu[N];
inline void shai_fa(){
miu[1]=1;
for(register int i=2;i<=50000;++i){
if(!ip[i])
miu[pr[++pr[0]]=i]=-1;
for(register int j=1;j<=pr[0]&&pr[j]*i<=50000;++j){
ip[pr[j]*i]=1;
if(i%pr[j]==0)break;
miu[i*pr[j]]=-miu[i];
}
}
}
int T;
int a,b,k;
int main(){
shai_fa();
scanf("%d",&T);
while(T--){
scanf("%d%d%d",&a,&b,&k);
a/=k;b/=k;
ans=0;
for(register int i=1;i<=min(a,b);++i)
ans+=1ll*miu[i]*(a/i)*(b/i);
printf("%lld\n",ans);
}
return 0;
}
容易知道[a'/d]单调不上升,且最多有2√a'种不同的取值。所以按取值分成√n个段分别处理,一个连续段内的和可以用预处理出的莫比乌斯函数前缀和求出
复杂度O(T√n)
AC根号做法
#include<cstdio>
typedef long long ll;
ll ans;
inline int min(int a,int b){return a<b?a:b;}
const int N=50011;
bool ip[N];
int pr[N],miu[N],sum[N];
inline void shai_fa(){
sum[1]=miu[1]=1;
for(register int i=2;i<=50000;++i){
if(!ip[i])
miu[pr[++pr[0]]=i]=-1;
for(register int j=1;j<=pr[0]&&pr[j]*i<=50000;++j){
ip[pr[j]*i]=1;
if(i%pr[j]==0)break;
miu[i*pr[j]]=-miu[i];
}
sum[i]=sum[i-1]+miu[i];
}
}
int T;
int a,b,k,pos;
int main(){
shai_fa();
scanf("%d",&T);
while(T--){
scanf("%d%d%d",&a,&b,&k);
a/=k;b/=k;
ans=0;
for(register int i=1;i<=min(a,b);i=pos+1){
pos=min(a/(a/i),b/(b/i));
ans+=1ll*(sum[pos]-sum[i-1])*(a/i)*(b/i);
}
printf("%lld\n",ans);
}
return 0;
}
类似题目BZOJ2301
http://www.lydsy.com/JudgeOnline/problem.php?id=2301
只不过多一个容斥
#include<cstdio>
typedef long long ll;
ll ans;
inline int min(int a,int b){return a<b?a:b;}
const int N=50011;
bool ip[N];
int pr[N],miu[N],sum[N];
inline void shai_fa(){
sum[1]=miu[1]=1;
for(register int i=2;i<=50000;++i){
if(!ip[i])
miu[pr[++pr[0]]=i]=-1;
for(register int j=1;j<=pr[0]&&pr[j]*i<=50000;++j){
ip[pr[j]*i]=1;
if(i%pr[j]==0)break;
miu[i*pr[j]]=-miu[i];
}
sum[i]=sum[i-1]+miu[i];
}
}
int T;
int a,b,c,d,k,pos;
inline void deal(int n,int m,ll type){
for(register int i=1;i<=min(n,m);i=pos+1){
pos=min(n/(n/i),m/(m/i));
ans+=type*(sum[pos]-sum[i-1])*(n/i)*(m/i);
}
}
int main(){
shai_fa();
scanf("%d",&T);
while(T--){
scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
--a;--c;
a/=k;b/=k;c/=k;d/=k;
ans=0;
deal(a,c,1ll);deal(a,d,-1ll);deal(c,b,-1ll);deal(b,d,1ll);
printf("%lld\n",ans);
}
return 0;
}