Codeforces 280C - Game on Tree

传送门:280C - Game on Tree


 

不知道期望是啥的请自行Baidu或Google,(溜了

题目大意,有一棵有根树,每次随机选择一个节点,将这个节点和它的子树删除,问将整棵树删除的期望次数

那我们就来想,如果要计算一个节点的期望的话每个节点和它的祖先是在决策范围内的,所以它的子树我们可以先不用管,需要预处理出每一个点有几个祖先,当然还要加上它本身

因为每一个点的随机变量都是1,所以只需要将概率计算出来求一个和就行,注意题目要求控制精度了。

代码(:逃

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int MAXN = (int(1e5)+3)*2;

int N, F[MAXN];
double Ans;
int u[MAXN], v[MAXN], first[MAXN], next[MAXN];

inline int read() {
	int x = 0, f = 1;
	char c = getchar();
	while(c < '0'||c > '9') {
		if(c == '-') f = -1;
		c = getchar();
	}
	while(c <= '9'&&c >= '0') {
		x = x*10+c-'0';
		c = getchar();
	}
	return x * f;
}

void dfs(int x, int from) {
	int k = first[x];
	while(k != -1) {
		if(v[k] == from) {k = next[k]; continue;}
		F[v[k]] = F[u[k]]+1;
		dfs(v[k], u[k]);
		k = next[k];
	}
}

int main() {
	N = read();
	memset(first, -1, sizeof(first));
	for(int i=1; i<=(N-1)*2; i++) {
		u[i] = read(), v[i] = read();
		next[i] = first[u[i]];
		first[u[i]] = i;
		i++;
		u[i] = v[i-1], v[i] = u[i-1];
		next[i] = first[u[i]];
		first[u[i]] = i;
	}
	F[1] = 1;
	dfs(1, 0);
	for(int i=1; i<=N; i++) {
		Ans += 1.0/double(F[i]);
	}
	printf("%.10lf", Ans);
}

  

posted @ 2018-06-17 14:58  Mystical-W  阅读(236)  评论(0编辑  收藏  举报