1. 程式人生 > >[Codeforces 839C] Journey

[Codeforces 839C] Journey

temp git getchar() printf dde head nbsp color ++

[題目鏈接]

http://codeforces.com/contest/839/problem/C

[算法]

概率DP

時間復雜度 : O(N)

[代碼]

#include<bits/stdc++.h>
using namespace std;
#define MAXN 100010

int tot , n;
int head[MAXN];
bool visited[MAXN];
double f[MAXN];

struct edge
{
        int to , nxt;
} e[MAXN << 1];

template 
<typename T> inline void chkmax(T &x,T y) { x = max(x,y); } template <typename T> inline void chkmin(T &x,T y) { x = min(x,y); } template <typename T> inline void read(T &x) { T f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == -
) f = -f; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - 0; x *= f; } inline void addedge(int u,int v) { tot++; e[tot] = (edge){v,head[u]}; head[u] = tot; } inline double dp(int u,int fa) { int cnt = 0; if (visited[u]) return
f[u]; for (int i = head[u]; i; i = e[i].nxt) { int v = e[i].to; if (v == fa) continue; cnt++; } if (cnt == 0) { visited[u] = true; return f[u] = 0; } f[u] = 1; for (int i = head[u]; i; i = e[i].nxt) { int v = e[i].to; if (v == fa) continue; f[u] += 1.0 / cnt * dp(v,u); } visited[u] = true; return f[u]; } int main() { read(n); for (int i = 1; i < n; i++) { int u , v; read(u); read(v); addedge(u,v); addedge(v,u); } memset(visited,false,sizeof(visited)); printf("%.10lf\n",dp(1,0)); return 0; }

[Codeforces 839C] Journey