您的位置:首页 > 其它

莫比乌斯反演 1004 BZOJ 2301

2016-08-01 22:30 225 查看
题意:

对于给出的 n 个询问,每次求有多少个数对 (x,y) ,

满足 a ≤ x ≤ b , c ≤ y ≤ d ,且 gcd(x,y) = k ,

gcd(x,y) 函数为 x 和 y 的最大公约数。

思路:

Ans(a~b,c~d)=Ans(b,d)-Ans(a-1,d)-Ans(b,c-1)+Ans(a-1,c-1)

求gcd(x,y)==k&& x<=n&&y<=m == gcd(x,y)==1 && x<=n/k && y<=m/k

这样会比直接求gcd(x,y)==k快上一倍

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
#define lowbit(x) (x&(-x))
typedef long long LL;
const int maxn = 1000005;
const int inf=(1<<28)-1;
#define maxp 100005
bool notprimes[maxp];
int primes[maxp];
int mu[maxp];
void get_mu()
{
memset(notprimes,false,sizeof(notprimes));
primes[0]=0;
mu[1]=1;
for(int i=2;i<maxp;++i)
{
if(!notprimes[i])
{
primes[++primes[0]]=i;
mu[i]=-1;
}
for(int j=1;j<=primes[0];++j)
{
if((LL)primes[j]*i>=maxp) break;
notprimes[i*primes[j]]=true;
if(i%primes[j])
{
mu[i*primes[j]]=-mu[i];
}
else
{
mu[i*primes[j]]=0;
break;//代表i不是素数,mu[i*primes[j]]必然是0
}
}
}
}

LL Pre[maxp];
int k;

LL solve(int n,int m)
{
n/=k,m/=k;
LL Ans=0;
int t=min(n,m),last;
for(int i=1;i<=t;i=last+1)
{
last=min(n/(n/i),m/(m/i));
Ans+=(LL)(Pre[last]-Pre[i-1])*(n/i)*(m/i);
}
return Ans;
}

int main()
{
get_mu();
Pre[0]=0;
for(int i=1;i<maxp;++i)
Pre[i]=Pre[i-1]+mu[i];
int T;
scanf("%d",&T);
while(T--)
{
int a,b,c,d;
scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
LL Ans=solve(b,d)-solve(a-1,d)-solve(b,c-1)+solve(a-1,c-1);
printf("%lld\n",Ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: