跳到正文

题解

Construction of a tree

xht约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月11日
篇幅
约 5 分钟
获赞
4

版本

  1. v1当前

Construction of a tree

题意

  • 给定 [1,n][1,n] 的 n−1n-1 个子集 E1…n−1E_{1\dots n-1}。
  • 问是否能从每个子集中选择两个元素,使得将这两个元素相连后形成一棵树,如果可以请构造一组方案。
  • n≤105n \le 10^5,∑i=1n−1∣Ei∣≤2×105\sum_{i=1}^{n-1} |E_i| \le 2 \times 10^5。

题解

考虑将 11 作为根,那么之后每条边都可以看成是一个点和其父亲的连边。

建立二分图,左边是点 2∼n2 \sim n,右边是子集 1∼n−11 \sim n - 1,若点 ii 在子集 jj 中则连边,那么如果有解就必须存在完备匹配。

任取一组完备匹配,从 11 开始构造树。一开始将 11 所在的所有点集的匹配点的父亲设为 11,然后从这些点递归下去。

如果递归到了所有点,则构造出了一组解,否则说明二分图不连通,从而一定无解。

Dinic 求二分图匹配,时间复杂度 O(mn)\mathcal O(m \sqrt n)。

代码

C++
namespace Dinic {
	const int N = 2e5 + 7, M = 2e6 + 7;
	const ll inf = 1e18;
	int n, S, T, d[N];
	int h[N], hi[N], e[M], t[M], tot;
	ll f[M], mxf;

	inline void add(int x, int y, ll z, bool o = 1) {
		e[++tot] = y, f[tot] = z, t[tot] = h[x], h[x] = tot;
		if (o) add(y, x, 0, 0);
	}

	inline bool bfs() {
		for (int i = 1; i <= n; i++) d[i] = 0;
		queue<int> q;
		q.push(S), d[S] = 1;
		while (q.size()) {
			int x = q.front();
			q.pop();
			for (int i = h[x]; i; i = t[i]) {
				int y = e[i];
				ll z = f[i];
				if (d[y] || !z) continue;
				q.push(y), d[y] = d[x] + 1;
				if (y == T) return 1;
			}
		}
		return 0;
	}

	ll dfs(int x, ll now = inf) {
		if (x == T) return now;
		ll rst = now;
		for (int &i = hi[x]; i; i = t[i]) {
			int y = e[i];
			ll z = f[i];
			if (d[y] != d[x] + 1 || !z) continue;
			ll k = dfs(y, min(z, rst));
			if (!k) d[y] = 0;
			else f[i] -= k, f[i^1] += k, rst -= k;
			if (!rst) break;
		}
		return now - rst;
	}

	inline void main() {
		while (bfs()) {
			for (int i = 1; i <= n; i++) hi[i] = h[i];
			ll now;
			while ((now = dfs(S))) mxf += now;
		}
	}

	inline void init(int _n, int _S, int _T) {
		n = _n, S = _S, T = _T, tot = 1, mxf = 0;
		for (int i = 1; i <= n; i++) h[i] = 0;
	}
}
using Dinic::add;

const int N = 1e5 + 7;
int n, f[N], fa[N], id[N];
set<int> e[N], g[N];
bool v[N];
pi ans[N];

int main() {
	rd(n), Dinic::init(2 * n, 1, 2 * n);
	for (int i = 1, c, x; i < n; i++) {
		add(1, i + 1, 1), add(i + n, 2 * n, 1);
		rd(c);
		while (c--) {
			rd(x), e[i].insert(x), g[x].insert(i);
			if (x == 1) continue;
			add(x, i + n, 1);
		}
	}
	Dinic::main();
	if (Dinic::mxf != n - 1) return print(-1), 0;
	for (int x = 1; x < n; x++)
		for (int i = Dinic::h[x+n]; i; i = Dinic::t[i])
			if (Dinic::e[i] <= n && Dinic::f[i]) f[x] = Dinic::e[i];
	queue<int> q;
	q.push(1);
	while (q.size()) {
		int x = q.front();
		q.pop();
		for (int y : g[x])
			if (!v[y]) v[y] = 1, fa[f[y]] = x, id[f[y]] = y, q.push(f[y]);
	}
	for (int i = 1; i < n; i++)
		if (!v[i]) return print(-1), 0;
	for (int i = 2; i <= n; i++) ans[id[i]] = mp(fa[i], i);
	for (int i = 1; i < n; i++) print(ans[i].fi, ans[i].se);
	return 0;
}
原文