codeforces 839C - Journey (dfs)
题目链接:https://codeforces.com/problemset/problem/839/C
dfs
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn = 100010;
int n;
int h[maxn],cnt = 0;
struct E{
int to,next;
}e[maxn*2];
void add(int u,int v){
e[++cnt].to = v;
e[cnt].next = h[u];
h[u] = cnt;
}
int deg[maxn],dep[maxn],sz[maxn];
double p[maxn],ans;
void dfs(int u,int par){
sz[u] = 1;
dep[u] = dep[par] + 1;
if(par==1) p[u] = p[par] * (1.0 / deg[par]);
else if(par!=0)p[u] = p[par] * (1.0 / (deg[par] - 1));
for(int i=h[u];i!=-1;i=e[i].next){
int v=e[i].to;
if(v==par) continue;
dfs(v,u);
sz[u] += sz[v];
}
if(sz[u] == 1){
ans += (dep[u]-1) * p[u];
}
}
ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }
int main(){
memset(h,-1,sizeof(h));
n = read();
ans = 0.0;
int u,v;
for(int i=1;i<n;++i){
u = read(),v = read();
add(u,v), add(v,u);
++deg[u], ++deg[v];
}
p[1] = 1.0;
dfs(1,0);
printf("%.7f\n",ans);
return 0;
}