1. 程式人生 > >bzoj 2301 HAOI2011 Problem b

bzoj 2301 HAOI2011 Problem b

main geo wap () prime turn line printf next

題目鏈接

BZOJ 2301 HAOI2011 Problem b

題解

\[\sum_{i=1}^n\sum_{j=1}^m[gcd(i,j)==k]\]
\[=\sum_{i=1}^{? \dfrac{n}{k}?}\sum_{j=1}^{?\dfrac{m}{k}?}[gcd(i,j)==1]\]
利用函數f(x)表示x|(gcd(i,j))中ij的對數,那麽原函數:
\[=\sum_{i=1}^{? \dfrac{n}{k}?}\sum_{j=1}^{?\dfrac{m}{k}?}\sum_{d|gcd(i,j)}\mu(d)\]
\[=\sum_{d=1}^{min(\dfrac{n}{k},\dfrac{m}{k})} \mu(d)*\sum_{d|i,i\leq\dfrac{n}{k}}\sum_{d|j,j\leq\dfrac{m}{k}}1\]


\[\sum_{d=1}^{min(?\dfrac{n}{k}?,?\dfrac{m}{k}?)} \mu(d)*?\dfrac{n}{k}?*?\dfrac{m}{k}?)\]
\(?\dfrac{n}{k}?\)最多只有\(2\sqrt{n}\)個取值,預處理\(\mu(d)\) \(O(\sqrt{n})\)回答

代碼

#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long LL;
const int maxn=50007;
inline int read() {
    int
x=0; char c=getchar(); while(c<'0'||c>'9')c=getchar(); while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar(); return x; } int n,prime[maxn]; bool vis[maxn];long long mu[maxn]; void get_wrrj() { mu[1]=1; for(int i=2;i<=maxn-1;i++) { if
(!vis[i]) prime[++prime[0]]=i,mu[i]=-1; for(int j=1;j<=prime[0]&&i*prime[j]<=maxn-1;j++) { vis[i*prime[j]]=1; if(i%prime[j]==0) { mu[i*prime[j]]=0;break; } mu[i*prime[j]]=-mu[i]; } } for(int i=1;i<=maxn-1;i++) mu[i]+=mu[i-1]; } LL calc(int n,int m,int k) { n/=k;m/=k; if(n>m) std::swap(n,m); LL ans=0;int next=0; for(int i=1;i<=n;i=next+1) { next=std::min(n/(n/i),m/(m/i)); ans+=(mu[next]-mu[i-1])*(n/i)*(m/i); } return ans; } int main() { get_wrrj(); int T=read(); for(int a,b,c,d,k;T--;) { a=read();b=read();c=read();d=read();k=read(); printf("%lld\n",calc(b,d,k)-calc(a-1,d,k)-calc(b,c-1,k)+calc(a-1,c-1,k)); } return 0; }

bzoj 2301 HAOI2011 Problem b