跳到正文

题解

题解:P4219 [BJOI2014] 大融合

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

文章信息

发布
2026年11月17日
收录
2026年11月18日
更新
2026年11月18日
篇幅
约 5 分钟
题目
P4219

版本

  1. v1当前

P4219 [BJOI2014] 大融合 题解。

前言:

这题怎么没有启发式合并做法啊?

做法:

预处理:

  1. 把询问离线下来,把所有的边先连起来得到一片森林。
  2. 将森林中的每一棵树的根节点与一个超级根连起来得到一棵树。
  3. 遍历这棵超级树,处理出每个节点的 dfs 序。
  4. 将所有的 dfs 序塞入 pbds 的 tree 中。

Q:这有什么用呢?

A:这样可以固定树的形态方便我们查询及合并。

询问:

  1. 直接启发式合并即可。
  2. 设深度更大的点为 ii,找出该联通块所有 dfs 序在 LiL_i 到 RiR_i 的点个数。
Why?

看看图片: downloaded-image_.jpg

其中 9 为超级根。

此时我们可以发现我们对于一条边 [a,b][a,b](设 bb 的深度更大),其中一边子树大小必然是这一联通块内的 dfs 序在 LbL_b 到 RbR_b 之间点的个数,因此可以直接对于 pbds 寻找即可。

AC Code
C++
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define lop(i, a, b) for (int i = (a); i < (b); i++)
#define dwn(i, a, b) for (int i = (a); i >= (b); i--)
#define mp(a, b) make_pair(a, b)
#define pr pair<int, int>
#define fir first
#define sec second
#define pb push_back
#define iosfst ios::sync_with_stdio(false);cin.tie(0), cout.tie(0)
using namespace std;
using namespace __gnu_pbds;
const int N = 3e5 + 10;
int n, m, tot, root, L[N], R[N], f[N], dep[N];
struct Query{
	char op;
	int x, y;
} q[N];
vector<int> G[N];
tree<pr, null_type, less<pr>, rb_tree_tag, tree_order_statistics_node_update> tr[N], h;
int find(int x) {
	if (x == f[x]) return x;
	return f[x] = find(f[x]);
}
void dfs(int p, int fa) {
	cout << p << ' ' << fa << '\n'; 
	L[p] = ++tot, dep[p] = dep[fa] + 1;
	lop (i, 0, G[p].size()) {
		int to = G[p][i];
		if (to == fa) continue;
		dfs(to, p);
	}
	R[p] = tot;
	return;
}
void merge(int x, int y) {
	if (tr[x].size() > tr[y].size()) {
		h.join(tr[x]);
		tr[x].join(tr[y]);
		tr[y].join(h);
	}
	f[x] = y;
	for (auto t : tr[x]) tr[y].insert(t);
	tr[x].clear();
	return;
}
signed main() {
	iosfst; 
	cin >> n >> m;
	rep (i, 1, m) cin >> q[i].op >> q[i].x >> q[i].y;
	rep (i, 1, n) f[i] = i;
	rep (i, 1, m) if (q[i].op == 'A') G[q[i].x].pb(q[i].y), G[q[i].y].pb(q[i].x), f[find(q[i].x)] = find(q[i].y);
	root = n + 1;
	rep (i, 1, n) if (f[i] == i) G[root].pb(i);
	dfs(root, 0);
	rep (i, 1, n) tr[i].insert(mp(L[i], i)), f[i] = i;
	rep (i, 1, m) {
		if (q[i].op == 'A') merge(find(q[i].x), find(q[i].y));
		else {
			int a = q[i].x, b = q[i].y;
			if (dep[a] > dep[b]) swap(a, b);
			int id = find(a);
			int l = tr[id].order_of_key(mp(L[b], b + 1)), r = tr[id].order_of_key(mp(R[b], 1e9));
			cout << (r - l + 1) * (tr[id].size() - r + l - 1) << '\n';
		}
	}
	return 0;
}
原文