P3455 [POI2007] ZAP-Queries

题意

\(\sum_{i = 1} ^ {n} \sum_{j = 1} ^ {m} [gcd(i, j) = k]\)

Sol

\[\begin{aligned} f(k) &= \sum_{i = 1} ^ {n} \sum_{j = 1} ^ {m} [\gcd(i, j) = k] \\ &= \sum_{i = 1} ^ {\lfloor \frac{x}{k} \rfloor} \sum_{j = 1} ^ {\lfloor \frac{y}{k} \rfloor} [\gcd(i, j) = 1] \\ &= \sum_{i = 1} ^ {\lfloor \frac{x}{k} \rfloor} \sum_{j = 1} ^ {\lfloor \frac{y}{k} \rfloor} \sum_{d | \gcd(i, j)} ^ {\min(x, y)} \mu(d) \\ &= \sum_{d = 1} ^ n \mu(d) \lfloor \frac{x}{kd} \rfloor \lfloor \frac{y}{kd} \rfloor \\ \end{aligned}\]

这个时候我们就可以做了。

直接套上整除分块即可。

时间复杂度 \(O(n + T \sqrt n)\)

Code

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <array>
#include <bitset>
#define int long long
using namespace std;
#ifdef ONLINE_JUDGE

#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
char buf[1 << 23], *p1 = buf, *p2 = buf, ubuf[1 << 23], *u = ubuf;

#endif
int read() {
	int p = 0, flg = 1;
	char c = getchar();
	while (c < '0' || c > '9') {
		if (c == '-') flg = -1;
		c = getchar();
	}
	while (c >= '0' && c <= '9') {
		p = p * 10 + c - '0';
		c = getchar();
	}
	return p * flg;
}
void write(int x) {
	if (x < 0) {
		x = -x;
		putchar('-');
	}
	if (x > 9) {
		write(x / 10);
	}
	putchar(x % 10 + '0');
}
const int N = 1e5 + 5;

array <int, N> p, mu;
bitset <N> vis;
int cnt;

void Euler(int n) {
	mu[1] = 1;
	for (int i = 2; i <= n; i++) {
		if (!vis[i]) {
			cnt++;
			p[cnt] = i;
			mu[i] = -1;
		}
		for (int j = 1; j <= cnt && i * p[j] <= n; j++) {
			vis[i * p[j]] = 1;
			if (i % p[j] == 0) {
				mu[i * p[j]] = 0;
				break;
			}
			mu[i * p[j]] = -mu[i];
		}
	}
	for (int i = 1; i <= n; i++)
		mu[i] += mu[i - 1];
}
void solve() {
	int n = read(), m = read(), k = read();
	n /= k, m /= k;
	if (n > m) swap(n, m);
	int res = 0, ans = 0;
	for (int i = 1; i <= n; i = res + 1) {
		res = min(n / (n / i), m / (m / i));
		ans += (mu[res] - mu[i - 1]) * (n / i) * (m / i);
	}
	write(ans), puts("");
}
signed main() {
	Euler(1e5);
	/* write(mu[114]), puts(""); */
	int T = read();
	while (T--) solve();
	return 0;
}
posted @ 2023-11-30 16:40  cxqghzj  阅读(3)  评论(0编辑  收藏  举报