跳到正文

题解

题解:AT_abc469_f [ABC469F] GCD Maximum Spanning Tree

srp_Ethan约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年8月4日
收录
2026年8月26日
更新
2026年11月11日
篇幅
约 3 分钟
获赞
2

版本

  1. v1当前

Link\mathcal{Link}

思路

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

如何用 O(nlog⁡n)\mathcal{O(n\log n)} 的时间求出每一个数的倍数的个数

我们可以开一个 10610^6 的数组统计每一个数出现的次数。然后再累加每一个数的倍数的出现次数之和。复杂度 O(n1+n2+⋯+nn)=O(n×(1+12+13+⋯+1n))=O(nlog⁡n)\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≤a1<a2<⋯<an≤1061\le a_1< a_2< \dots< a_n\le 10^6。所以我们可以开一个 10610^6 的数组统计每一个数是否出现(所有数互不相同)。然后用上述 trick,枚举每一个数能否作为最大公约数,再枚举它的倍数是否出现。剩下的部分类似 Kruskal。

代码

AC
C++
#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;
}
原文
存档评论1 条抓取于