hdu4405 概率dp

来源:互联网 发布:linux 别名 编辑:程序博客网 时间:2024/06/11 06:22

Problem Description
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.


Input
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.



Output
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.


测试案例:

input:

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


output:

1.1667
2.3441


大致题意:现在有个飞行棋,棋盘从0-n共n个格子,你现在从0开始走,最后要走到大于等于n的位置才能结束,棋盘上有些飞行通道,比如到达2能直接飞到5,然后继续飞到7这种,但是一个格子不会有从他出发的多个飞行通道,你有一个骰子,每次可以投1-6,问从0结束游戏的投色子次数期望是多少




解题思路:设dp[i]表示i到n的期望,那么可以得到dp[i]=(dp[i+1]+dp[i+2]+dp[i+3]+dp[i+4]+dp[i+5]+dp[i+6])/6+1,另外注意飞行航道和处理离终点6以内的特殊点。

代码:

#include <cstdio>#include <cstring>#include <algorithm>#include <vector>using namespace std;const int maxn=100010;const double t=(double)1/(double)6;int g[maxn],n,m;double dp[maxn];double go(int i,int d){    if (i+d>=n)        return t;    int pos=g[i+d];    while (pos!=-1)    {        if (g[pos]==-1)            break;        else        {            pos=g[pos];        }    }    if (pos==-1)        pos=i+d;    return t*(dp[pos]+1);}int main(){    int i,j,x,y;    while (scanf("%d%d",&n,&m)==2)    {        if (n==0&&m==0)            break;        for (i=0;i<=n;i++)        {            g[i]=-1;            dp[i]=0;        }        for (i=0;i<m;i++)        {            scanf("%d%d",&x,&y);            g[x]=y;        }        for (i=n-1;i>=0;i--)        {            for (j=1;j<=6;j++)            {                dp[i]+=go(i,j);            }        }        printf("%.4lf\n",dp[0]);    }}


0 0
原创粉丝点击