BZOJ 2301 Problem b(莫比乌斯反演+分块优化)

时间:2021-08-04 11:52:56

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=37166

题意:对于给出的n个询问,每次求有多少个数对(x,y),满足a≤x≤b,c≤y≤d,且gcd(x,y) = k,gcd(x,y)函数为x和y的最大公约数。

思路:本题使用莫比乌斯反演要利用分块来优化,那么每次询问的复杂度降为2*sqrt(n)+2*sqrt(m)。注意到 n/i ,在连续的k区间内存在,n/i=n/(i+k)。所有对这连续的区间可以一次求出来,不过要先预处理mu的前n项和。

code:

 #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MAXN = ; bool check[MAXN];
int primes[MAXN];
int mu[MAXN];
int sum[MAXN];
LL a, b, c, d, k; void moblus()
{
memset(check, false, sizeof(check));
mu[] = ;
int cnt = ;
for (int i = ; i < MAXN; ++i) {
if (!check[i]) {
primes[cnt++] = i;
mu[i] = -;
}
for (int j = ; j < cnt; ++j) {
if (i * primes[j] > MAXN) break;
check[i * primes[j]] = true;
if (i % primes[j] == ) {
mu[i * primes[j]] = ;
break;
} else {
mu[i * primes[j]] = -mu[i];
}
}
}
sum[] = ;
for (int i = ; i < MAXN; ++i) {
sum[i] = sum[i - ] + mu[i];
}
} LL cal(LL n, LL m)
{
if (n > m) swap(n, m);
n /= k;
m /= k;
LL ret = ;
for (int i = , la = ; i <= n; i = la + ) {
la = min(n/(n/i), m/(m/i));
ret += (n / i) * (m / i) * (sum[la] - sum[i - ]);
}
return ret;
} int main()
{
moblus();
int nCase;
scanf("%d", &nCase);
while (nCase--) {
scanf("%lld %lld %lld %lld %lld", &a, &b, &c, &d, &k);
LL ans = cal(b, d) - cal(a - , d) - cal(b, c - ) + cal(a - , c - );
printf("%lld\n", ans);
}
return ;
}