【dfs】codeforces Journey

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

【AC】

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>

using namespace std;
const int maxn=2e5+3;
struct edge
{
    int to;
    int nxt; 
}e[maxn];
int head[maxn];
int tot;
int dep[maxn];
double ans;
int n;
void init()
{
    memset(head,-1,sizeof(head));
    tot=0;
}
void add(int u,int v)
{
    e[tot].to=v;
    e[tot].nxt=head[u];
    head[u]=tot++;
}

void dfs(int u,int pa,double p)
{
//    cout<<u<<" "<<p<<" "<<dep[u]<<endl;
    int cnt=0;
    for(int i=head[u];i!=-1;i=e[i].nxt)
    {
        int v=e[i].to;
        if(v==pa) continue;
        cnt++;
    }
    for(int i=head[u];i!=-1;i=e[i].nxt)
    {
        int v=e[i].to;
        if(v==pa) continue;
        dep[v]=dep[u]+1;
        dfs(v,u,p/(double)cnt);
    }
    if(cnt==0)
    {
//        cout<<"叶节点"<<u<<endl;
        ans+=(double)dep[u]*p;
    }
    
}
int main()
{
    while(~scanf("%d",&n))
    {
        init();
        memset(dep,0,sizeof(dep));
        int u,v;
        for(int i=0;i<n-1;i++)
        {
            scanf("%d%d",&u,&v);
            add(u,v);
            add(v,u);
        }
        ans=0.0;
        dep[1]=0;
        dfs(1,0,1);
        printf("%.15f\n",ans);
    }
    return 0;    
}

【注意】

不能先把所有的分枝数乘起来得到cnt,最后到叶节点再计算概率1/cnt,这样cnt会爆的,一开始就是因为这个WA了

posted @ 2017-08-13 22:36  shulin15  阅读(158)  评论(0编辑  收藏  举报