题解:AT_abc469_f [ABC469F] GCD Maximum Spanning Tree

· · 题解

\mathcal{Link}

思路

首先科普一下这个经典的 trick。

:::info[如何用 \mathcal{O(n\log n)} 的时间求出每一个数的倍数的个数] 我们可以开一个 10^6 的数组统计每一个数出现的次数。然后再累加每一个数的倍数的出现次数之和。复杂度 \mathcal{O(\frac{n}{1}+\frac{n}{2}+\dots +\frac{n}{n})=\mathcal{O(n\times (1+\frac{1}{2}+\frac{1}{3}+\dots+\frac{1}{n}))}}=\mathcal{O(n\log n)}。 :::

对于这道题,1\le a_1< a_2< \dots< a_n\le 10^6。所以我们可以开一个 10^6 的数组统计每一个数是否出现(所有数互不相同)。然后用上述 trick,枚举每一个数能否作为最大公约数,再枚举它的倍数是否出现。剩下的部分类似 Kruskal。

代码

:::success[AC]

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define _i128 __int128
#define oo 1000000000000000000
#define pii pair<int, int>
#define fi first
#define se second
#define for1(i, a, b) for (int i = (a); i <= (b); i++)
#define for2(i, a, b) for (int i = (a); i >= (b); i--)
#define pr(x) cout << #x << " = " << (x) << "\n"
const int N = 1e6 + 5;
int TT = 1;
int a[N], fa[N];
bool p[N];

int get(int x)
{
    return x == fa[x] ? x : fa[x] = get(fa[x]);
}

void solve()
{
    int n; cin >> n;
    for1(i, 1, n) cin >> a[i], p[a[i]] = 1;
    for1(i, 1, 1e6) fa[i] = i;
    int ans = 0, cnt = 0;
    for2(i, 1e6, 1){
        int lst = 0;
        for (int j = i; j <= 1e6; j += i)
            if (p[j]){
                if (lst){
                    int u = get(lst), v = get(j);
                    if (fa[u] != fa[v])
                        cnt++, ans += i, fa[u] = v;
                    if (cnt == n - 1)
                        return cout << ans << "\n", void();
                }
                lst = j;
            }
    }
}

signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    //freopen(".in", "r", stdin);
    //freopen(".out", "w", stdout);
    //cin >> TT;
    while (TT--)
        solve();

    return 0;
}

:::