BZOJ 2301: [HAOI2011]Problem b
2301: [HAOI2011]Problem b
Time Limit: 50 Sec Memory Limit: 256 MBSubmit: 4035 Solved: 1820
[Submit][Status][Discuss]
Description
对于给出的n个询问,每次求有多少个数对(x,y),满足a≤x≤b,c≤y≤d,且gcd(x,y) = k,gcd(x,y)函数为x和y的最大公约数。
Input
第一行一个整数n,接下来n行每行五个整数,分别表示a、b、c、d、k
Output
共n行,每行一个整数表示满足要求的数对(x,y)的个数
Sample Input
2
2 5 1 5 1
1 5 1 5 2
2 5 1 5 1
1 5 1 5 2
Sample Output
14
3
HINT
100%的数据满足:1≤n≤50000,1≤a≤b≤50000,1≤c≤d≤50000,1≤k≤50000
Source
分析:
这题和http://www.cnblogs.com/neighthorn/p/6215096.htmlZap不是一样么...只不过变成去见了...容斥一下好了...
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<algorithm> 2 #include<iostream> 3 #include<cstring> 4 #include<cstdio> 5 //by NeighThorn 6 using namespace std; 7 //大鹏一日同风起,扶摇直上九万里 8 9 const int maxn=50000+5; 10 11 int a,b,c,d,k,cas,cnt,miu[maxn],vis[maxn],prime[maxn]; 12 13 inline long long calc(int x,int y){ 14 int lala=min(x,y);long long ans=0; 15 for(int i=1,r;i<=lala;i=r+1){ 16 r=min(x/(x/i),y/(y/i)); 17 ans+=(long long)(miu[r]-miu[i-1])*(x/i)*(y/i); 18 } 19 return ans; 20 } 21 22 signed main(void){ 23 memset(vis,0,sizeof(vis));miu[1]=1; 24 for(int i=2;i<=50000;i++){ 25 if(!vis[i]) 26 vis[i]=1,prime[++cnt]=i,miu[i]=-1; 27 for(int j=1;j<=cnt&&prime[j]*i<=50000;j++){ 28 vis[i*prime[j]]=1; 29 if(i%prime[j]==0){ 30 miu[i*prime[j]]=0;break; 31 } 32 miu[i*prime[j]]=-miu[i]; 33 } 34 } 35 for(int i=2;i<=50000;i++) 36 miu[i]+=miu[i-1]; 37 scanf("%d",&cas); 38 while(cas--){ 39 scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);a--,c--; 40 printf("%lld\n",calc(a/k,c/k)+calc(b/k,d/k)-calc(a/k,d/k)-calc(b/k,c/k)); 41 } 42 return 0; 43 }
by NeighThorn