Michael has a telecontrol robot. One day he put the robot on a loop with n cells. The cells are numbered from 1 to n clockwise.
At first the robot is in cell 1. Then Michael uses a remote control to send m commands to the robot. A command will make the robot walk some distance. Unfortunately the direction part on the remote control is broken, so for every command the robot will chose a direction(clockwise or anticlockwise) randomly with equal possibility, and then walk w cells forward.
Michael wants to know the possibility of the robot stopping in the cell that cell number >= l and <= r after m commands.
Input
There are multiple test cases.
Each test case contains several lines.
The first line contains four integers: above mentioned n(1≤n≤200) ,m(0≤m≤1,000,000),l,r(1≤l≤r≤n).
Then m lines follow, each representing a command. A command is a integer w(1≤w≤100) representing the cell length the robot will walk for this command.
The input end with n=0,m=0,l=0,r=0. You should not process this test case.
Output
For each test case in the input, you should output a line with the expected possibility. Output should be round to 4 digits after decimal points.
Sample Input
3 1 1 2
1
5 2 4 4
1
2
0 0 0 0
Sample Output
0.5000
0.2500
分析:
题意:
第一行输入4个数:n,m.l.r;n表示圆盘的值是从1~n,然后是m次移动,最后l和r分别是区间的左右端点;然后是m行,每行表示这次移动的距离w;输出移动m次最后在l到r这个区间的概率。
解析:
我们用dp[i][i%2]表示移动k次出现在j这个位置的概率;所以我们可以得出状态转移方程:
dp[j][i%2]=(dp[(j-w+n)%n][!(i%2)]+dp[(j+w)%n][!(i%2)])*0.5;
注意:这道题很卡时间,开始没有考虑到(j+w)%n==0的情况,着使得答案错误,然后我用到了memset()这个函数,但是一直超时!!所以,千万不要用这个函数!
代码:
#include<iostream>
#include<cstdio>
using namespace std;
float dp[205][2];
int main()
{
int n,m,l,r,w;
while(scanf("%d%d%d%d",&n,&m,&l,&r)&&(n+m+l+r))
{
for(int j=0;j<n;j++)
{
dp[j][1]=dp[j][0]=0;
}
dp[0][0]=1.0;
for(int i=1;i<=m;i++)
{
scanf("%d",&w);
for(int j=0;j<n;j++)
{
dp[j][i%2]=(dp[(j+n-w)%n][!(i%2)]+dp[(j+w)%n][!(i%2)])*0.5;
}
}
float sum=0;
for(int i=l-1;i<r;i++)
{
sum+=dp[i][m%2];
}
printf("%.4lf\n",sum);
}
return 0;
}