dfs跑树,每次记录路径个数及到达当前结点的概率,期望值等于到达各个叶子结点的步数*概率值的和,注意n=1时的特判。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <list>
#include <stack>
#include <cstring>
#include <queue>
#include <map>
#include <string>
using namespace std;
#define MAX 205
#define ll long long
#define INF 0x3f3f3f3f
#define mod 1000000007
vector<int> G[100005];
bool vis[100005];
double p, ans;
void dfs(int c, int v,double p) {
vis[v] = true;
bool f = false;
int si = G[v].size() - 1;
if (si) {
if(v != 1) p /= si;
else p /= (si + 1);
}
for (int i = 0; i <= si; ++i) {
int t = G[v][i];
if (!vis[t]) {
f = true;
dfs(c + 1, t,p);
}
}
if (!f) {
ans = ans + c * p;
}
}
int main()
{
freopen("a.txt", "r", stdin);
freopen("b.txt", "w", stdout);
int n, x, y;
cin >> n;
if (n == 1) {
printf("0\n");
return 0;
}
for (int i = 1; i < n; ++i) {
scanf("%d%d", &x, &y);
G[x].push_back(y);
G[y].push_back(x);
}
dfs(0, 1,1);
printf("%.15lf\n", ans);
return 0;
}