CF1540B Tree Array 题解
CF1540B Tree Array 题解
首先题目的时间复杂度一定是一个 \(O(n^3)\) 状物。一定会有一个 \(n\) 来枚举根节点,那么一个根内要 \(O(n^2)\) 地解决问题。
考虑整个序列的期望是困难的,转而考虑每个点对 \((x,y)\) 的期望。注意到 \((x,y)\) 具有父子关系时,它的贡献是确定为 \(0/1\) 的。当 \((x,y)\) 关系不确定时,考虑只有在 \(\operatorname{LCA}(x,y)\) 之后才会出现不同的部分。考虑当前情况下 \(\operatorname{LCA}(x,y)\) 只有 \(x,y\) 这两条支路是有效的,走其它的路对 \((x,y)\) 的贡献没有影响。这样一来问题就转变为了有两个大小分别为 \(a,b\) 的栈,各有 \(\dfrac{1}{2}\) 的概率弹出一个,问第一个栈先弹完的概率。于是考虑 dp:初始状态是 \(dp_{0,i}=1\),转移上是考虑上一个弹的是哪个栈,式子是 \(dp_{i,j}=\dfrac{dp_{i-1,j}+dp_{i,j-1}}{2}\)。然后这题就完了。
代码:
#include <bits/stdc++.h>
#define N 205
#define int long long
#define mod 1000000007
using namespace std;
int n;
struct Node {
	int to, nxt;
} e[N << 1];
int head[N], cnt;
void add(int u, int v) {
	e[++cnt].to = v;
	e[cnt].nxt = head[u];
	head[u] = cnt;
}
int dep[N], f[N], son[N], siz[N], top[N];
void dfs1(int x, int fa) {
	dep[x] = dep[fa] + 1;
	f[x] = fa;
	siz[x] = 1;
	for (int i = head[x]; i; i = e[i].nxt) {
		int y = e[i].to;
		if (y == fa) continue;
		dfs1(y, x);
		siz[x] += siz[y];
		if (siz[y] > siz[son[x]]) son[x] = y;
	}
}
void dfs2(int x, int t) {
	top[x] = t;
	if (!son[x]) return;
	dfs2(son[x], t);
	for (int i = head[x]; i; i = e[i].nxt) {
		int y = e[i].to;
		if (y != f[x] && y != son[x]) dfs2(y, y);
	}
}
int LCA(int x, int y) {
	while (top[x] != top[y]) {
		if (dep[top[x]] < dep[top[y]]) swap(x, y);
		x = f[top[x]];
	}
	return dep[x] > dep[y] ? y : x;
}
int qpow(int x, int y) {
	int ans = 1;
	while (y) {
		if (y & 1) ans = ans * x % mod;
		x = x * x % mod;
		y >>= 1;
	}
	return ans;
}
void ad(int &x, int y) {
	x = (x + y) % mod;
}
#define __(a) memset(a, 0, sizeof a)
void clr() {
	__(dep), __(f), __(son), __(siz), __(top);
}
int ans, dp[N][N];
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin >> n;
	for (int i = 1; i < n; i++) {
		int x, y;
		cin >> x >> y;
		add(x, y);
		add(y, x);
	}
	const int inv2 = qpow(2, mod - 2);
	for (int i = 0; i <= n; i++) dp[0][i] = 1;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			ad(dp[i][j], (dp[i][j - 1] + dp[i - 1][j]) % mod * inv2 % mod);
	for (int rt = 1; rt <= n; rt++) {
		clr();
		dfs1(rt, 0);
		dfs2(rt, rt);
		for (int a = 1; a < n; a++)
			for (int b = a + 1; b <= n; b++) {
				int l = LCA(a, b);
				if (l == b) ad(ans, 1);
				else if (l != a) ad(ans, dp[dep[b] - dep[l]][dep[a] - dep[l]]);
			}
	}
	cout << ans * qpow(n, mod - 2) % mod << "\n";
	return 0;
}

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号