# 14289: 【原4289】Journey

### 题目描述

author: Guo Linsong 原OJ链接：https://acm.sjtu.edu.cn/OnlineJudge-old/problem/4289

## Description

There are $n$ cities and $n - 1$ roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be $1$. The journey starts in the city $1$. What is the expected length (expected value of length) of their journey?

## Input Format

The first line contains a single integer $n (1\leq n \leq 100000)$ — number of cities. Then $n - 1$ lines follow. The $i$-th line of these lines contains two integers $u_i$ and $v_i$ ($1 \leq ui, vi \leq n$) — the cities connected by the $i$-th road. It is guaranteed that one can reach any city from any other by the roads.

## Output Format

Print a number — the expected length of their journey. The journey starts in the city $1$.

## Sample Input 1

4
1 2
1 3
2 4


## Sample Output 1

1.50


## Sample Input 2

5
1 2
1 3
3 4
2 5


## Sample Output 2

2.00


## zqy2018's solution

/*
See the solution at https://github.com/zqy1018/sjtu_oj_solutions/blob/master/solutions/sjtu4289.md
*/
#include <cstdio>
#define INF 2000000000
using namespace std;
typedef long long ll;
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();}
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
int n;
int at[100005], nxt[200005], to[200005], cnt = 0;
int d[100005] = {0};
double p[100005] = {0}, ans = 0;
void dfs(int cur, int fa){
int cnt = 0;
for (int i = at[cur]; i; i = nxt[i]){
int v = to[i];
if (v == fa) continue;
++cnt;
}
if (!cnt){
ans += p[cur] * d[cur];
return ;
}
for (int i = at[cur]; i; i = nxt[i]){
int v = to[i];
if (v == fa) continue;
p[v] = p[cur] * (1.0 / cnt);
d[v] = d[cur] + 1;
dfs(v, cur);
}
}
void init(){
for (int i = 1; i < n; ++i){
to[++cnt] = v, nxt[cnt] = at[u], at[u] = cnt;
to[++cnt] = u, nxt[cnt] = at[v], at[v] = cnt;
}
}
void solve(){
p[1] = 1.0;
dfs(1, 0);
printf("%.2lf\n", ans);
}
int main(){
init();
solve();
return 0;
}