Three Chairs

· · 题解

这里是一篇比较离谱的暴力题解。

题目传送门:Three Chairs

我们首先把 a 数组从小到大排序,然后问题就变成了求三元组 (i, j, k)(i < j < k,\gcd(a_i, a_k) = 1) 的个数。

考虑枚举 j,然后每次就是求有多少对二元组 (i, j) 满足 i < j,k > j,\gcd(a_i, a_k) = 1。

可以考虑每次把 j 往右移一位,考虑对数 now 会发生什么变化。

如果我们设 pre_i 表示第 i 个数之前与 a_i 互质的数的个数,suc_i 表示第 i 个数之后与 a_i 互质的数的个数。

明显每次从 j - 1 变成 j,now 就要加上 suc_{j - 1} - pre_j。

然后问题就变成了如何求 pre_i 和 suc_i,这里以 pre_i 为例,suc_i 同理。

我们可以考虑直接容斥,由于 a_i \le 3 \times 10 ^ 5,而 2 \times 3 \times 5 \times 7 \times 11 \times 13 \times 17 > 3 \times 10 ^ 5,所以 a_i 的不同的质因子个数最多只有 6 个。

所以我们开一个桶 cnt,cnt(x) 表示当前多少数能够被 x 整除,假设 a_i = p_1 ^ {k_1} \times p_2 ^ {k_2} \times \cdots \times p_m ^ {k_m}。

设 S = \{p_1, p_2, \cdots, p_m\}

pre_i = \sum_{T \subseteq S} (-1)^{|T|} \times cnt(\prod_{x \in T} x)

然后实现好一点就可以过了,时间复杂度 \Theta(n \sqrt n + 2 ^ 6 \times n)。

#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
int n, a[300005];
int cnt[300005], pre[300005], suc[300005], mul[ 1 << 6 ];
int main() {
    #ifndef ONLINE_JUDGE
    freopen("code.in", "r", stdin);
    #endif
    ios :: sync_with_stdio(0), cin.tie(0);
    cin >> n;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
    }
    sort(a + 1, a + n + 1);
    memset(cnt, 0, sizeof(cnt));
    for (int i = 1; i <= n; ++i) {
        int now = a[i];
        vector <int> fac;
        for (int j = 2; j * j <= now; ++j) {
            if (now % j == 0) {
                fac.push_back(j);
                while (now % j == 0) now /= j;
            }
        }
        if (now > 1) fac.push_back(now);
        int m = fac.size(), ans = cnt[1];
        mul[0] = 1, ++cnt[1];
        for (int s = 1; s < 1 << m; ++s) {
            int t = __builtin_ctz(s), b = __builtin_popcount(s);
            mul[s] = mul[ s ^ 1 << t ] * fac[t];
            if (b & 1) ans -= cnt[ mul[s] ];
            else ans += cnt[ mul[s] ];
            ++cnt[ mul[s] ];
        }
        pre[i] = ans; 
    }
    memset(cnt, 0, sizeof(cnt));
    for (int i = n; i; --i) {
        int now = a[i];
        vector <int> fac;
        for (int j = 2; j * j <= now; ++j) {
            if (now % j == 0) {
                fac.push_back(j);
                while (now % j == 0) now /= j;
            }
        }
        if (now > 1) fac.push_back(now);
        int m = fac.size(), ans = cnt[1];
        mul[0] = 1, ++cnt[1];
        for (int s = 1; s < 1 << m; ++s) {
            int t = __builtin_ctz(s), b = __builtin_popcount(s);
            mul[s] = mul[ s ^ 1 << t ] * fac[t];
            if (b & 1) ans -= cnt[ mul[s] ];
            else ans += cnt[ mul[s] ];
            ++cnt[ mul[s] ];
        }
        suc[i] = ans; 
    }
    i64 ans = 0, now = 0;
    for (int i = 2; i < n; ++i) {
        now += suc[ i - 1 ] - pre[i];
        ans += now;
    }
    cout << ans << '\n';
    return 0;
}