CF839 C 树形DP 期望

给一颗树,求从根出发路径长度的期望是多少。

树形DP 要想清楚期望的计算

 

/** @Date    : 2017-08-12 23:09:41
  * @FileName: C.cpp
  * @Platform: Windows
  * @Author  : Lweleth (SoungEarlf@gmail.com)
  * @Link    : https://github.com/
  * @Version : $Id$
  */
#include <bits/stdc++.h>
#define LL long long
#define PII pair<int ,int>
#define MP(x, y) make_pair((x),(y))
#define fi first
#define se second
#define PB(x) push_back((x))
#define MMG(x) memset((x), -1,sizeof(x))
#define MMF(x) memset((x),0,sizeof(x))
#define MMI(x) memset((x), INF, sizeof(x))
using namespace std;

const int INF = 0x3f3f3f3f;
const int N = 1e5+20;
const double eps = 1e-6;


vector<int>edg[N];
int vis[N];
double f[N];
double dfs(int x, int pre)
{
	int flag = 0;
	for(auto i: edg[x])
	{
		if(i == pre)
			continue;
		flag++;
		dfs(i, x);
		f[x] += f[i];
	}
	if(flag)
		f[x] = 1.0*f[x]/flag + 1;
}

int main()
{
	int n;
	while(cin >> n)
	{
		MMF(vis);
		for(int i = 0; i <= n; i++)
			edg[i].clear();
		for(int i = 0; i < n - 1; i++)
		{
			int x, y;
			scanf("%d%d", &x, &y);
			edg[x].PB(y);
			edg[y].PB(x);
		}
		dfs(1, -1);
		//cout << ans << " "<< cnt << endl;
		//printf("%.10lf\n", (1.0000000*ans/cnt));
		printf("%.10lf\n", f[1]);
	}

    return 0;
}
posted @ 2017-08-29 18:58  Lweleth  阅读(253)  评论(0编辑  收藏  举报