【Luogu3455】【POI2007】ZAP-Queries(莫比烏斯反演)
阿新 • • 發佈:2017-12-02
stream bre 似的 string 獲得 計算 getc ans contain
這題會超時
那麽,考慮計算的時候。
\(g(i)=(\frac bk/i)·(\frac dk/i)\)
其中一定會有連續的一段使得\(g(i)\)的值是不會變化的
(Gay神說這叫數論分塊,復雜度\(O(\sqrt{n}\))
因此,預處理出\(\mu\)的前綴和
利用數論分塊即可在\(O(T\sqrt{n})的復雜度裏計算出來\)
【Luogu3455】【POI2007】ZAP-Queries(莫比烏斯反演)
題面
題目描述
FGD正在破解一段密碼,他需要回答很多類似的問題:對於給定的整數a,b和d,有多少正整數對x,y,滿足x<=a,y<=b,並且gcd(x,y)=d。作為FGD的同學,FGD希望得到你的幫助。
輸入輸出格式
輸入格式:
The first line of the standard input contains one integer nn (1\le n\le 50?0001≤n≤50 000),denoting the number of queries.
The following nn lines contain three integers each: aa, bb and dd(1\le d\le a,b\le 50?0001≤d≤a,b≤50 000), separated by single spaces.
Each triplet denotes a single query.
輸出格式:
Your programme should write nn lines to the standard output. The ii‘th line should contain a single integer: theanswer to the ii‘th query from the standard input.
輸入輸出樣例
輸入樣例#1:
2
4 5 2
6 4 3
輸出樣例#1:
3
2
題解
和前面那一道HDU1695GCD是一樣的
直接蒯過代碼
然後就會獲得70分
這樣做的復雜度是\(O(Tn)\)
這題會超時
那麽,考慮計算的時候。
\(g(i)=(\frac bk/i)·(\frac dk/i)\)
其中一定會有連續的一段使得\(g(i)\)的值是不會變化的
(Gay神說這叫數論分塊,復雜度\(O(\sqrt{n}\))
因此,預處理出\(\mu\)的前綴和
利用數論分塊即可在\(O(T\sqrt{n})的復雜度裏計算出來\)
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define MAX 101000
inline int read()
{
int x=0,t=1;char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
if(ch=='-')t=-1,ch=getchar();
while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
return x*t;
}
int mu[MAX],pri[MAX],tot,s[MAX];
long long g[MAX],n,a,b,K;
bool zs[MAX];
void Get()
{
zs[1]=true;mu[1]=1;
for(int i=2;i<=n;++i)
{
if(!zs[i])pri[++tot]=i,mu[i]=-1;
for(int j=1;j<=tot&&i*pri[j]<=n;++j)
{
zs[i*pri[j]]=true;
if(i%pri[j])mu[i*pri[j]]=-mu[i];
else {mu[i*pri[j]]=0;break;}
}
}
for(int i=1;i<=n;++i)s[i]=s[i-1]+mu[i];
}
long long Calc(int a,int b,int K)
{
a/=K;b/=K;
long long ans=0;
int i=1;
if(a>b)swap(a,b);
while(i<=a)
{
int j=min(a/(a/i),b/(b/i));
ans+=1ll*(s[j]-s[i-1])*(a/i)*(b/i);
i=j+1;
}
return ans;
}
int main()
{
n=100000;
Get();
int T=read();
while(T--)
{
a=read();b=read();K=read();
printf("%lld\n",Calc(a,b,K));
}
return 0;
}
【Luogu3455】【POI2007】ZAP-Queries(莫比烏斯反演)