【Codeforces Round #428 (Div. 2) C】Journey

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

Description

给一棵树,每当你到一个点x的时候,你进入x的另外一每一个出度的概率都是相同的(但不能到你之前到过的点);
问你从1出发走过的路径的期望长度;

Solution

从1出发,看看到达某个点的概率是多少;
到了叶子节点的时候,概率乘距离累加到答案上.

NumberOf WA

0

Reviw


Code

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)
#define ri(x) scanf("%d",&x)
#define rl(x) scanf("%lld",&x)
#define rs(x) scanf("%s",x+1)
#define oi(x) printf("%d",x)
#define ol(x) printf("%lld",x)
#define oc putchar(' ')
#define os(x) printf(x)
#define all(x) x.begin(),x.end()
#define Open() freopen("F:\rush.txt","r",stdin)
#define Close() ios::sync_with_stdio(0)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 1e5;

int n;
double dp[N+10],ans;
vector <int> G[N+10];

void dfs(int x,int fa,double now,double P){
    int len = G[x].size();
    if (x!=1 && len==1){
        ans += P*now;
        return;
    }

    double p;
    if (x==1)
        p = 1/(1.0*len);
    else
        p = 1/(1.0*(len-1));
    rep1(i,0,len-1){
        int y = G[x][i];
        if (y==fa) continue;
        dfs(y,x,now+1,P*p);
    }
}

int main(){
    //Open();
    //Close();
    ri(n);
    rep1(i,1,n-1){
        int x,y;
        ri(x),ri(y);
        G[x].pb(y),G[y].pb(x);
    }
    dfs(1,0,0,1);
    printf("%.13f
",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626122.html