CF547C Mike and Foam

· · 题解

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

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

对于加入(或删除)的数 x,找到所有质因数 p(最多 6 个)进行容斥,先假定 x 与集合中所有数字都互质,再排除集合中每个 p_i 的倍数,但是所有形如 p_i\times p_j 的都算重复了需要再加回来,以此类推。具体来说,选 i 个质因数的乘积总和 的贡献在 i 为偶数时为正否则为负,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 = 1 时要 ++ans 因为 \gcd(x, x) = x 仅在 x = 1 时成立。

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

展示代码:

#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;
}