您的位置:首页 > 其它

hdu 4405 概率dp

2014-10-14 20:48 316 查看
http://acm.hdu.edu.cn/showproblem.php?pid=4405

[align=left]Problem Description[/align]
Hzz loves aeroplane chess very much. The chess map contains N+1 grids labeled from 0 to N. Hzz starts at grid 0. For each step he throws a dice(a dice have six faces with equal probability to face up and the numbers on the faces are
1,2,3,4,5,6). When Hzz is at grid i and the dice number is x, he will moves to grid i+x. Hzz finishes the game when i+x is equal to or greater than N.

There are also M flight lines on the chess map. The i-th flight line can help Hzz fly from grid Xi to Yi (0<Xi<Yi<=N) without throwing the dice. If there is another flight line from Yi, Hzz can take the flight line continuously. It is granted that there is
no two or more flight lines start from the same grid.

Please help Hzz calculate the expected dice throwing times to finish the game.

 

 

[align=left]Input[/align]
There are multiple test cases.

Each test case contains several lines.

The first line contains two integers N(1≤N≤100000) and M(0≤M≤1000).

Then M lines follow, each line contains two integers Xi,Yi(1≤Xi<Yi≤N).  

The input end with N=0, M=0.

 

 

[align=left]Output[/align]
For each test case in the input, you should output a line indicating the expected dice throwing times. Output should be rounded to 4 digits after decimal point.

 

 

[align=left]Sample Input[/align]

2 0
8 3
2 4
4 5
7 8
0 0

 

 

[align=left]Sample Output[/align]

1.1667
2.3441

 

在一个数轴0~n,i位置掷骰子得到j,则由i位置变为i+j位置,除此之外还有一些可以互达的点,比如说a->b,b->c,那么到达a位置后不用再次置骰子我们可以直接到达b并能传递的到达c。问掷骰子次数的数学期望值?

解题思路:概率dp,转移方程为:dp[i]+=dp[i-j]*1/6,(j=1~6)可以互达的直接相等即可。

代码如下:

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;

int n,m,f[100010];
double dp[100010];

int main()
{
while(~scanf("%d%d",&n,&m))
{
if(n==0&&m==0)
break;
memset(dp,0,sizeof(dp));
memset(f,-1,sizeof(f));
for(int i=0;i<m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
f[a]=b;
}
for(int i=n-1;i>=0;i--)
{
if(f[i]!=-1)
dp[i]=dp[f[i]];
else
{
for(int j=1;j<=6;j++)
dp[i]+=dp[i+j]*1.0/6;
dp[i]+=1;
}
}
printf("%.4lf\n",dp[0]);
}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: