【CF280C】Game on Tree

题目

题目链接:https://codeforces.ml/problemset/problem/280/C
给出一棵树,每次随机等概率选择一未染黑的点,将它及其子树染黑。问期望多少次操作可以将树全部染黑。
(nleq 10^5)

思路

考虑一个点 (x),它需要被操作的期望是 (frac{1}{mathrm{dep}_x})。因为这玩意等价于随机一个长度为 (n) 的序列,它所有祖先节点都在他后面的期望。
所以答案就是把所有点深度的倒数加起来。
时间复杂度 (O(n))

代码

#include <bits/stdc++.h>
using namespace std;

const int N=100010;
int n,tot,head[N],dep[N];
double ans;

struct edge
{
	int next,to;
}e[N*2];

void add(int from,int to)
{
	e[++tot]=(edge){head[from],to};
	head[from]=tot;
}

void dfs(int x,int fa)
{
	dep[x]=dep[fa]+1;
	ans+=1.0/dep[x];
	for (int i=head[x];~i;i=e[i].next)
		if (e[i].to!=fa) dfs(e[i].to,x);
}

int main()
{
	memset(head,-1,sizeof(head));
	scanf("%d",&n);
	for (int i=1,x,y;i<n;i++)
	{
		scanf("%d%d",&x,&y);
		add(x,y); add(y,x);
	}
	dfs(1,0);
	printf("%.10lf",ans);
	return 0;
}
原文地址:https://www.cnblogs.com/stoorz/p/14279026.html