跳到正文

个人记录

CF547C Mike and Foam

Believe_in_dreams约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年8月4日
更新
2026年8月4日
篇幅
约 4 分钟

版本

  1. v1当前

若干次操作向集合内加入或删除数字,每次操作后查询互质数对个数,n≤4×105,ai≤5×105n\le 4\times 10^5, a_i\le 5\times 10^5。

维护 sis_i 表示集合中是 ii 的倍数的数的个数:在加入数时将其所有因数 dd 都 ++s[d]。

对于加入(或删除)的数 xx,找到所有质因数 pp(最多 66 个)进行容斥,先假定 xx 与集合中所有数字都互质,再排除集合中每个 pip_i 的倍数,但是所有形如 pi×pjp_i\times p_j 的都算重复了需要再加回来,以此类推。具体来说,选 ii 个质因数的乘积总和 的贡献在 ii 为偶数时为正否则为负,ans += s[1], ans -= s[p[1]] + s[p[2]] ... + s[p[t]], ans += s[p[1] * p[2]] + s[p[1] * p[3]] ... + s[p[t - 1] * p[t]] ...

注意 x=1x = 1 时要 ++ans 因为 gcd⁡(x,x)=x\gcd(x, x) = x 仅在 x=1x = 1 时成立。

时间复杂度 O(m×(6×26+Vlog⁡V))≈3×108\mathcal O(m \times (6\times 2^6 + \frac{\sqrt V}{\log \sqrt V}))\approx 3\times 10^8,注意 ans 需要使用 long long 类型。

展示代码:

C++
#include<bits/stdc++.h>
using namespace std;
constexpr int N = 2e5 + 5, M = 5e5 + 5;
int n, q, a[N], s[M];
long long ans;
int stk[9], cnt[9], top;
int tot, pr[M], v[M];
bool in[N];
void dfs(int x, int mul, int c) {
	if (x > top) {
		s[mul] += c;
		return;
	}
	for (int i = 0; i <= cnt[x]; ++i)
		dfs(x + 1, mul, c), mul *= stk[x];
}
signed main() {
	for (int i = 2; i <= 5e5; ++i) {
		if (!v[i]) v[i] = i, pr[++tot] = i;
		for (int j = 1; j <= tot and 1ll * i * pr[j] <= 5e5; ++j) {
			v[i * pr[j]] = pr[j];
			if (i % pr[j] == 0) break;
		}
	}
	cin >> n >> q;
	for (int i = 1; i <= n; ++i) cin >> a[i];
	while (q--) {
		int id, x, del = 0, c;
		cin >> id, x = a[id], c = (in[id] ? -1 : 1);
		while (top) cnt[top--] = 0;
		while (x != 1) {
			if (v[x] != stk[top])
				stk[++top] = v[x];
			x /= v[x], ++cnt[top];
		}
		for (int i = 0; i < (1 << top); ++i) {
			int mul = 1, w = c;
			for (int j = 1; j <= top; ++j)
				if (i & (1 << (j - 1)))
					mul *= stk[j], w *= -1;
			ans += w * s[mul];
		}
		ans += (in[id] and a[id] == 1), dfs(1, 1, c), in[id] ^= 1, cout << ans << '\n';
	}
	return 0;
}
原文