BZOJ1101: [POI2007] Zap — Solution
Main Idea
This is a really good problem; it contains a lot of the techniques of number theory.
First, this is a multi-query problem and the number of queries is very large, so we gave up on using Euler's totient function. Consider using the properties of the Möbius function to tackle it, and start analyzing from that angle.
Let's review the definition of the Möbius function:
\[ \mu(x) = \begin{cases} 0, 在x中存在指数大于一的质因子 \\ 1, 在x中质因子指数都为1且质因子个数为偶数 \\ -1, 在x中质因子质数都为1且质因子个数为奇数 \end{cases} \]
Let's look at the answer expression: \(\sum_{i,j} [gcd(x,y)=d]\). We first transform the \(gcd\) part:
\[gcd(\frac{x}{d}, \frac{y}{d}) = 1\]
Clearly, the number of such pairs is \( \lfloor \frac{x}{d} \rfloor*\lfloor \frac{y}{d} \rfloor \). We consider inclusion–exclusion: because if we accumulate by brute force, we get a lot of extra parts that shouldn't be there, for example the parts that are multiples of both 2 and 3.
So the final answer expression is:
\[\sum_{i=1}^{min\{a,b\}} \mu(i)*\lfloor \frac{x}{i} \rfloor*\lfloor \frac{y}{i} \rfloor \]
Here there is a trick: we can prove that on the integer segment \([x, min\{ \lfloor \frac{a}{\lfloor \frac{a}{x} \rfloor} \rfloor, \lfloor \frac{b}{\lfloor \frac{b}{x} \rfloor} \rfloor \} ]\), the value of \(\lfloor \frac{x}{i} \rfloor*\lfloor \frac{y}{i} \rfloor\) is the same, so we just multiply it by the prefix sum. In the worst case there are \(O(\sqrt{a}+\sqrt{b})\) such segments, so the time complexity is fairly low.
Code
// BZ1101.cpp
#include <bits/stdc++.h>
#define ll int
using namespace std;
const int MAX_N = 5e4 + 200;
ll mobi[MAX_N], sum[MAX_N], n;
bool vis[MAX_N];
int main()
{
for (int i = 1; i < MAX_N; i++)
mobi[i] = 1;
for (int i = 2; i < MAX_N; i++)
{
if (vis[i])
continue;
mobi[i] = -1;
for (int j = 2; i * j < MAX_N; j++)
{
vis[i * j] = true;
if (j % i == 0)
mobi[i * j] = 0;
else
mobi[i * j] *= -1;
}
}
for (int i = 1; i < MAX_N; i++)
sum[i] = sum[i - 1] + mobi[i];
scanf("%d", &n);
while (n--)
{
int a, b, k, gx;
scanf("%d%d%d", &a, &b, &k);
a /= k, b /= k;
int ans = 0;
for (int i = 1; i <= min(a, b); i = gx + 1)
{
gx = min(a / (a / i), b / (b / i));
ans += (sum[gx] - sum[i - 1]) * (a / i) * (b / i);
}
printf("%d\n", ans);
}
return 0;
}