题解:POI2007 ZAP-Queries 【莫比乌斯反演】

题意:
i = 1 n j = 1 m [ g c d ( i , j ) = = d ] 求 \sum_{i=1}^n\sum_{j=1}^m [ gcd(i,j)==d ]

这个题目很明显就是一个莫比乌斯反演的板子题
f ( x ) = i = 1 n j = 1 m [ g c d ( i , j ) = x ] 我们令 f(x)=\sum_{i=1}^n\sum_{j=1}^m[gcd(i,j)=x]
根据莫比乌斯反演的基本定理
g ( x ) = x d f ( d ) = i = 1 n j = 1 m [ x g c d ( i , j ) ] g(x)=\sum_{x|d}f(d)=\sum_{i=1}^n\sum_{j=1}^m[x|gcd(i,j)]
[ x g c d ( i , j ) ] \because[x|gcd(i,j)]
x i x j \therefore x|i\text{且}x|j
g ( x ) = i = 1 n j = 1 m [ x g c d ( i , j ) ] = i = 1 n x j = 1 m x = n x m x g(x)=\sum_{i=1}^n\sum_{j=1}^m[x|gcd(i,j)]=\sum_{i=1}^{\lfloor\frac{n}{x}\rfloor}\sum_{j=1}^{\lfloor\frac{m}{x}\rfloor}=\lfloor\frac{n}{x}\rfloor\lfloor\frac{m}{x}\rfloor
f ( x ) = x d g ( d ) μ ( d x ) = x d μ ( d x ) n d m d f(x)=\sum_{x|d}g(d)\mu\left(\frac{d}{x}\right)=\sum_{x|d}\mu\left(\frac{d}{x}\right)\lfloor\frac{n}{d}\rfloor\lfloor\frac{m}{d}\rfloor
x d μ ( d x ) n d m d = i = 1 n x μ ( i ) n i x m i x = i = 1 n x μ ( i ) n x i m x i \sum_{x|d}\mu\left(\frac{d}{x}\right)\lfloor\frac{n}{d}\rfloor\lfloor\frac{m}{d}\rfloor=\sum_{i=1}^{\lfloor\frac{n}{x}\rfloor}\mu(i)\lfloor\frac{n}{ix}\rfloor\lfloor\frac{m}{ix}\rfloor=\sum_{i=1}^{\lfloor\frac{n}{x}\rfloor}\mu(i)\frac{\lfloor\frac{n}{x}\rfloor}{i}\frac{\lfloor\frac{m}{x}\rfloor}{i}
到了这一步,只需要运用数论分块进行处理,把复杂度降到 O ( n ) O\left(\sqrt{n}\right)

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define re register
#define gc getchar()
#define ll long long
inline int read()
{
	re int x(0); re char ch(gc);
	while(ch>'9'||ch<'0') ch=gc;
	while(ch>='0'&&ch<='9') x=(x*10)+(ch^48),ch=gc;
	return x;
}
const int N=50050;
int mu[N],pri[N],sum[N],vis[N],cnt;
void get_mu(int n)	//线性筛求mu函数
{
	mu[1]=1;
	for(int i=2;i<=n;++i)
	{
		if(!vis[i])
			mu[i]=-1,pri[++cnt]=i;
		for(int j=1;j<=cnt&&i*pri[j]<=n;++j)
		{
			vis[i*pri[j]]=1;
			if(i%pri[j]==0) break;
			else mu[i*pri[j]]=-mu[i];
		}
	}
	for(int i=1;i<=n;++i) sum[i]=sum[i-1]+mu[i];	//处理前缀和
}
void work()
{
	int a=read(),b=read(),d=read();
	int n=min(a,b),ans=0;
	for(int l=1,r;l<=n;l=r+1)	//数论分块优化
	{
		r=min(a/(a/l),b/(b/l));
		ans+=(a/(l*d))*(b/(l*d))*(sum[r]-sum[l-1]);
	}
	cout<<ans<<endl;
}
int main()
{
	int T=read();
	get_mu(50050);
	while(T--) work();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43464026/article/details/88550537