跳到正文

题解

题解:P7854 「EZEC-9」GCD Tree

喵仔牛奶约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年5月5日
收录
2025年12月12日
更新
2026年9月20日
篇幅
约 4 分钟
获赞
2
题目
P7854

版本

  1. v1当前

Solution

考虑一定有解怎么做。

进行观察:

  • 儿子一定是父亲的倍数。
  • 相同权值的点可以只保留一个,剩下的点当成保留的点的儿子即可。
  • 一个点在子树内是最小值。
  • 父亲是儿子最大的存在的因数。

按权值从大到小枚举点 xx,枚举所有权值是 xx 倍数的点 yy。如果 yy 没有父亲,那么根据第四个观察,xx 必然是 yy 的父亲。

这样就 O(vlog⁡v)\mathcal O(v\log v) 求出了一个构造。

考虑判定是否有解。假设无解,存在一对 x,yx,y,使得 z=lca(x,y)z=\text{lca}(x,y),az≠gcd⁡(ax,ay)a_z\neq\gcd(a_x,a_y)。

枚举 gcd⁡(ax,ay)=p\gcd(a_x,a_y)=p,如果权值是 pp 的倍数的点构成的子树超过一棵,那么从两棵子树内各取一个点出来就不合法。可能出现 p∣gcd⁡(ax,ay)p\mid\gcd(a_x,a_y) 被判掉的情况,但如果这样,在 p=gcd⁡(ax,ay)p=\gcd(a_x,a_y) 就已经判掉了。因此合法充要条件是对于所有 pp,权值是 pp 的倍数的点构成的子树不超过一棵。

怎么判定呢?在枚举 pp 的过程中同步建树,在没有判掉无解前,森林中的一棵树中权值是 pp 的倍数的点最多构成一个子树。

证明:假设存在两棵子树,从两棵子树内各取一个点,记为 x,yx,y,z=lca(x,y)z=\text{lca}(x,y)。由于 az∣gcd⁡(ax,ay)a_z\mid\gcd(a_x,a_y),有 gcd⁡(ax,ay)>az\gcd(a_x,a_y)>a_z。由于没有被判掉无解, p=gcd⁡(ax,ay)>zp=\gcd(a_x,a_y)>z。从大到小枚举,zz 不可能被加入,矛盾。

因此,使用并查集,维护每个点在的树的根,枚举倍数判断是不是有超过一种根即可。

复杂度 O(vlog⁡nlog⁡n)\mathcal O(v\log n\log n)。不会分析并查集复杂度,也许可以分析到更低?

Code

C++
#include <bits/stdc++.h>
#define REP(i, l, r) for (int i = (l); i <= (r); ++ i)
#define DEP(i, r, l) for (int i = (r); i >= (l); -- i)
#define fi first
#define se second
#define pb emplace_back
#define mems(x, v) memset((x), (v), sizeof(x))
#define SZ(x) (int)(x).size()
#define ALL(x) (x).begin(), (x).end()
using namespace std;
namespace Milkcat {
	typedef long long LL;
	typedef pair<LL, LL> pii;
	const int N = 1e6 + 5;
	int n, m, x, b[N], fa[N], p[N];
	vector<int> s[N];
	int find(int x) { return (!p[x] ? x : p[x] = find(p[x])); }
	int main() {
		cin >> n;
		REP(i, 1, n) cin >> x, b[x] = i, s[x].pb(i), m = max(m, x);
		DEP(i, m, 1) {
			set<int> s;
			REP(j, 2, m / i) {
				int x = b[i * j];
				if (!x) continue;
				if (b[i] && !fa[x]) fa[x] = b[i], p[x] = b[i];
				s.insert(find(x));
			}
			if (b[i]) s.insert(b[i]);
			if (SZ(s) > 1) { cout << "-1\n"; return 0; }
		}
		REP(i, 1, m) for (int x : s[i])
			if (x != b[i]) fa[x] = b[i];
		REP(i, 1, n) cout << fa[i] << ' ';
		cout << '\n';
		return 0;
	}
}
int main() {
	cin.tie(0)->sync_with_stdio(0);
	int T = 1;
	while (T --) Milkcat::main();
	return 0;
}
原文