3036: 绿豆蛙的归宿
Time Limit: 2 Sec Memory Limit: 128 MBSubmit: 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
1 2 1
1 3 2
2 3 3
3 4 4
Sample Output
7.00
HINT
对于100%的数据 N<=100000,M<=2*N
Source
期望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]);
}
本文介绍了一道关于概率动态规划的经典算法题目——绿豆蛙寻归宿。题目要求在有向无环图中计算从起点到终点路径长度的期望值。文章提供了完整的C++代码实现,通过深度优先搜索结合期望DP的方法解决此问题。
1538

被折叠的 条评论
为什么被折叠?



