[BZOJ]3036 绿豆蛙的归宿 期望dp

本文介绍了一道关于概率动态规划的经典算法题目——绿豆蛙寻归宿。题目要求在有向无环图中计算从起点到终点路径长度的期望值。文章提供了完整的C++代码实现,通过深度优先搜索结合期望DP的方法解决此问题。

3036: 绿豆蛙的归宿

Time Limit: 2 Sec   Memory Limit: 128 MB
Submit: 614   Solved: 434
[ Submit][ Status][ Discuss]

Description

随着新版百度空间的下线,Blog宠物绿豆蛙完成了它的使命,去寻找它新的归宿。

给出一个有向无环的连通图,起点为1终点为N,每条边都有一个长度。绿豆蛙从起点出发,走向终点。
到达每一个顶点时,如果有K条离开该点的道路,绿豆蛙可以选择任意一条道路离开该点,并且走向每条路的概率为 1/K 。
现在绿豆蛙想知道,从起点走到终点的所经过的路径总长度期望是多少?

Input

第一行: 两个整数 N M,代表图中有N个点、M条边
第二行到第 1+M 行: 每行3个整数 a b c,代表从a到b有一条长度为c的有向边

Output


从起点到终点路径总长度的期望值,四舍五入保留两位小数。


Sample Input

4 4
1 2 1
1 3 2
2 3 3
3 4 4

Sample Output

7.00

HINT



对于100%的数据  N<=100000,M<=2*N

Source

[ Submit][ Status][ Discuss]


HOME Back


期望dp水题...

#include<stdio.h>
#include<queue>
using namespace std;
const int maxn = 100005;
queue<int> q;
bool vis[maxn];
double dp[maxn];
int out[maxn], h[maxn], num, n, m, x, y, z;
inline const int read(){
	register int f = 1, x = 0;
	register char ch = getchar();
	while(ch < '0' || ch > '9') {if(ch == '-') f = -1;ch = getchar();}
	while(ch >= '0' && ch <= '9') x = (x<<3) + (x<<1) + ch - '0', ch = getchar();
	return f * x;
}
struct edge{ int nxt, v, w;}e[maxn * 2];
inline void add(int u, int v, int w){ e[++num].v = v, e[num].nxt = h[u], e[num].w = w, h[u] = num;}
void dfs(int u){
	if(vis[u]) return;
	vis[u] = true;
	for(int i = h[u]; i; i = e[i].nxt){
		int v = e[i].v;
		dfs(v); dp[u] += dp[v] + e[i].w;
	}
	if(out[u]) dp[u] /= out[u];
}
int main(){
	n = read(), m = read();
	for(register int i = 1; i <= m; ++i) x = read(), y = read(), z = read(), add(x, y, z), out[x]++;
	dfs(1);
	printf("%.2f\n", dp[1]);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值