#DFS、期望# Codeforces Round #428 (Div. 2)
题目链接:https://codeforces.com/contest/839/problem/C
C. Journey
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? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.
Input
The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities.
Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road.
It is guaranteed that one can reach any city from any other by the roads.
Output
Print a number — the expected length of their journey. The journey starts in the city 1.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Description
由 n 个顶点 n-1 条边构成的以 1 为根的树,从根出发,等概率的往其子树走,求走过的路径长度的期望。
Solution
DFS.
例如:
对5、6、7号结点期望求和即可。
需要注意的是,除了 1 号结点之外,其余结点均有父节点,所以在求其子树时需要减一,减去父节点,即:G[x].size()-1。
Code
#pragma GCC diagnostic error "-std=c++11"
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#define fi first
#define se second
#define mst(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const double eps = 1e-9;
const int Mod = 1e9 + 7;
const int MaxN = 1e5 + 5;
vector<int> G[MaxN];
int vis[MaxN];
int n;
double DFS(int x) {
vis[x] = 1;
double sum = 0.0;
for(int i = 0; i < G[x].size(); i++) {
int u = G[x][i];
if(!vis[u]) {
sum += DFS(u) + 1;
}
}
int p = G[x].size() - (x != 1);
return p ? (sum / p) : 0;
}
int main()
{
//ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
scanf("%d", &n);
for(int i = 1; i < n; i++) {
int u, v; scanf("%d %d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
printf("%.6lf\n", DFS(1));
return 0;
}