Aeroplane chess(HDU-4405)(概率DP)

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.

Sample Input

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

Sample Output

1.1667
2.3441

题意:跳棋有0~n个格子,每个格子X可以摇一次色子,色子有六面p(1=<p<=6),概率相等,可以走到X+p的位置,有些格子不需要摇色子就可以直接飞过去。问从0出发到达n或超过n摇色子的次数的期望。

思路:我们设一个times数组表示每个格子到达终点的平均次数,然后我们反推期望,便可以实现这道题。

AC代码:

#include <bits/stdc++.h>
typedef long long ll;
const int maxx=100010;
const int inf=0x3f3f3f3f;
using namespace std;
double times[maxx];
int a[maxx];
int n,m;
int main()
{
	int x,y;
	while(cin>>n>>m)
	{
		if(n==0)
            break;
		memset(a,0,sizeof(a));
		for(int i=0; i<m; i++)
		{
			cin>>x>>y;
			a[x]=y;
		}
		memset(times,0,sizeof(times));
		for(int i=n-1; i>=0; i--)
		{
			if (a[i])
			times[i]=times[a[i]];
			else times[i]=(times[i+1]+times[i+2]+times[i+3]+times[i+4]+times[i+5]+times[i+6])/6+1;
		}
		cout<<fixed<<setprecision(4)<<times[0]<<endl;
	}
	return 0;
}
发布了204 篇原创文章 · 获赞 16 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43846139/article/details/104015671