CF 428 div2 C. Journey

题目在这里>_<

题意

给你一颗树,从结点1出发,到每个没到过的点等概率,不会到走过的点。问走过路程长度的期望值。

思路

这题比赛20分钟写完代码,结果因为一些比赛外部因素一个小时才交。。。不过1A还是很开心的。
说正经的,因为这是一颗树,所以每次必然会走到叶子结点停下来。因此。我们只需要算从根到每个叶子的概率即可。也就是说,我们只需要dfs一遍算出到每个叶子的概率,再乘上路径长度求和即为答案。

代码

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <iostream>
#include <map>
#include <set>
//#define test
using namespace std;
const int Nmax=1e6+7;
typedef long long ll;
int n;
vector<int> son[Nmax];
double ans;
const double eps=1e-16;
void dfs(int now,int fa,int step,double g)
{
    //printf("now:%d fa:%d step:%d g:%lf\n",now,fa,step,g);
    if(son[now].size()==1 && son[now][0]==fa)
    {
        ans+=step*g;
        //printf("step:%d g:%lf\n",step,g);
    }
    int num=(int)son[now].size();
    int t=num;
    if(fa!=0)
        t--;
    for(int i=0;i<num;i++)
    {
        if(son[now][i]==fa)
            continue;
        //printf("now:%d t:%d\n",now,t);
        dfs(son[now][i],now,step+1,g*1.0/t);
    }
}
int main()
{
    #ifdef test
    #endif
    //freopen("3.in","r",stdin);
    scanf("%d",&n);
    int x,y;
    for(int i=1;i<n;i++)
    {
        scanf("%d%d",&x,&y);
        son[x].push_back(y);
        son[y].push_back(x);
    }
    //for(int i=1;i<=n;i++)
        //for(int j=0;j<(int)son[i].size();j++)
            //printf("%d %d\n",i,son[i][j]); 
    dfs(1,0,0,1.0);
    printf("%.15lf\n",ans+eps);
    return 0;
    }