Codeforces 839C Journey(dfs+概率)

41 篇文章 0 订阅
32 篇文章 0 订阅

很简单啦,注意到他只有n-1条边,那他一定是一棵树,没有环的.
所以只需要计算到达每个尽头的距离*每一次选路线时的概率就好了.

/*  xzppp  */
#include <iostream>
#include <vector>
#include <set>
#include <queue>
#include <map>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <list>
#include <math.h>
#include <iomanip>
using namespace std;
#define FFF freopen("in.txt","r",stdin);freopen("out.txt","w",stdout);
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mp make_pair
typedef long long  LL;
typedef unsigned long long ULL;
const int MAXN = 100000;
const int  INF = 0x7fffffff;
const int MOD = 1e9+7;
vector<int > G[MAXN+17];
int num = 0;
double ans = 0;
bool vis[MAXN+17];
void dfs(int x,double chac,int dis)
{
    vis[x] = 1;
    double temp = 1.0;
    if(x!=0&&G[x].size()>1) temp = 1.0/(G[x].size()-1);
    if(x==0) 
    {
        temp = 1.0/(G[x].size());
    }
    //cout<<x<<"  "<<temp<<G[x].size()<<endl;
    for (int i = 0; i < G[x].size(); ++i)
    {
        if(!vis[G[x][i]])
            dfs(G[x][i],chac*temp,dis+1);
    }
    if(G[x].size()==1)
    {
        //cout<<chac<<endl;
        ans += chac*dis;
    }
    return;
}
int main()
{
    //FFF
    int n;
    cin>>n;
    for (int i = 0; i < n-1; ++i)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        u--;v--;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    dfs(0,1.0,0);
    cout<<fixed<<setprecision(15)<<ans<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值