[POI2007]ZAP-Queries

[POI2007]ZAP-Queries

题目大意:

给出 \(a,b,d\),求满足 \(1 \leq x \leq a,1 \leq y \leq b\),且 \(\gcd(x,y)=d\) 的二元组 \((x,y)\) 的数量。

输入格式

输入第一行一个整数 \(n\),代表要回答的问题个数。
接下来 \(n\) 行,每行三个整数 \(a,b,d\)

输出格式

对于每组询问,输出一个整数代表答案。

数据范围

\(1 \leq n \leq 50000,1 \leq d \leq {a,b} \leq 50000\)

解析

特别小巧的题,很短,很快能看完,也很快能懵逼
不过,稍有点数论知识的同志,能榨出一点东西来
套路推式子先!!
题目给出的式子

\[\sum_{i=1}^a \sum_{j=1}^b [\gcd(i,j)=d] \]

现在我们进行深造

\[\begin{aligned} \sum_{i=1}^a \sum_{j=1}^b [\gcd(i,j)=d] &=\sum_{i=1}^a \sum_{j=1}^b [\gcd(\frac{i}{d},\frac{j}{d})=1] \\ &=\sum_{d|i}^a \sum_{d|j}^b [\gcd(\frac{i}{d},\frac{j}{d})=1] \\ &=\sum_{i=1}^{\lfloor \frac{a}{d} \rfloor} \sum_{j=1}^{\lfloor \frac{b}{d} \rfloor} [\gcd(i,j)=1] \\ \end{aligned} \]

瞅一瞅,爽!
莫比乌斯反演的第一条性质

\[\sum_{d|n}^n \mu(d) = [n=1] \]

二话不说,套式子!!

\[\begin{aligned} \sum_{i=1}^{\lfloor \frac{a}{d} \rfloor} \sum_{j=1}^{\lfloor \frac{b}{d} \rfloor} [\gcd(i,j)=1] &=\sum_{i=1}^{\lfloor \frac{a}{d} \rfloor} \sum_{j=1}^{\lfloor \frac{b}{d} \rfloor} \sum_{k|\gcd(i,j)}^{\gcd(i,j)} \mu(k) \\ &=\sum_{k=1}^{\min(\lfloor \frac{a}{d} \rfloor,\lfloor \frac{b}{d} \rfloor)} \mu(k) \sum_{i=1}^{\lfloor \frac{a}{d} \rfloor} \sum_{j=1}^{\lfloor \frac{b} {d} \rfloor}1 \\ &=\sum_{k=1}^{\min(\lfloor \frac{a}{d} \rfloor,\lfloor \frac{b}{d} \rfloor)} \mu(k) \lfloor \frac{\lfloor \frac{a}{d} \rfloor}{k} \rfloor \lfloor \frac{\lfloor \frac{b} {d} \rfloor}{k} \rfloor \end{aligned} \]

预处理出 \(\mu\) 的前缀和,然后数论分块
时间复杂度: \(O(\sqrt{\lfloor \frac{a}{d} \rfloor} + \sqrt{\lfloor \frac{b}{d} \rfloor})\)

代码

#include<cstdio>
#include<iostream>
using namespace std;

const int N = 5e4;
int a , b , d , T , mu[N + 5] , vis[N + 5] , prime[N + 5] , tot;

inline int solve(int a , int b , int d)
{
	register int n = a / d , m = b / d , res = 0 , j = 0;
	for(register int k = 1; k <= min(n , m); k = j + 1)
	{
		j = min(n / (n / k) , m / (m / k));
		res += (n / k) * (m / k) * (mu[j] - mu[k - 1]);
	}
	return res;
}

inline void getmu()
{
	vis[0] = vis[1] = 1 , mu[1] = 1;
	for(register int i = 2; i <= N + 5; i++)
	{
		if (vis[i] == 0) prime[++tot] = i , mu[i] = -1;
		for(register int j = 1; j <= tot && prime[j] * i <= N + 5; j++)
		{
			vis[prime[j] * i] = 1;
			if (i % prime[j] == 0) break;
			mu[prime[j] * i] = -mu[i];
		}
	}
	for(register int i = 1; i <= N + 5; i++) mu[i] += mu[i - 1];
}

int main()
{
	scanf("%d" , &T);
	getmu();
	while (T--)
	{
		scanf("%d%d%d" , &a , &b , &d);
		printf("%d\n" , solve(a , b , d));
	}	
}
posted @ 2020-01-12 09:16  leiyuanze  阅读(103)  评论(0编辑  收藏  举报