hdu4035 Maze(概率dp)

hdu4035

题目

一颗树形的迷宫,对于每个房间,有几率被杀回到房间1,有几率逃出去,有几率随机到相邻的房间,问逃出去的概率。

思路

http://www.cnblogs.com/kuangbin/archive/2012/10/03/2711108.html
推公式的概率dp,精妙之处在于E[i] = ki*E[1] + ei*0 + (1-ki-ei)/m*( E[father[i]]+1 + ∑( E[child[i]]+1 ) );以及设对每个结点:E[i] = Ai*E[1] + Bi*E[father[i]] + Ci;学到了

代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>

using namespace std;

typedef long long ll;

const int MAXN=10010;
const double eps=1e-9;
double k[MAXN],e[MAXN];
double A[MAXN],B[MAXN],C[MAXN];

vector<int>vec[MAXN];

bool dfs(int t,int pre)
{
    int m=vec[t].size();
    A[t]=k[t];
    B[t]=(1-k[t]-e[t])/m;
    C[t]=1-k[t]-e[t];
    double temp=0;
    for(int i=0; i<m; i++)
    {
        int v=vec[t][i];
        if(v==pre) continue;
        if(!dfs(v,t))return false;
        A[t]+=(1-k[t]-e[t])/m*A[v];
        C[t]+=(1-k[t]-e[t])/m*C[v];
        temp+=(1-k[t]-e[t])/m*B[v];
    }
    if(fabs(temp-1)<eps) return false;
    A[t]/=(1-temp);
    B[t]/=(1-temp);
    C[t]/=(1-temp);
    return true;
}

int main()
{
    int T,n,u,v,kase=1;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(int i=1; i<=n; i++)vec[i].clear();
        for(int i=1; i<n; i++)
        {
            scanf("%d%d",&u,&v);
            vec[u].push_back(v);
            vec[v].push_back(u);
        }
        for(int i=1; i<=n; i++)
        {
            scanf("%lf%lf",&k[i],&e[i]);
            k[i]/=100;
            e[i]/=100;
        }
        printf("Case %d: ",kase++);
        if(dfs(1,-1)&&fabs(1-A[1])>eps)
        {
            printf("%.6lf\n",C[1]/(1-A[1]));
        }
        else printf("impossible\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值