题目描述
Mary stands in a strange maze, the maze looks like a triangle(the first layer have one room,the second layer have two rooms,the third layer have three rooms …). Now she stands at the top point(the first layer), and the KEY of this maze is in the lowest layer’s leftmost room. Known that each room can only access to its left room and lower left and lower right rooms .If a room doesn’t have its left room, the probability of going to the lower left room and lower right room are a and b (a + b = 1 ). If a room only has it’s left room, the probability of going to the room is 1. If a room has its lower left, lower right rooms and its left room, the probability of going to each room are c, d, e (c + d + e = 1). Now , Mary wants to know how many steps she needs to reach the KEY. Dear friend, can you tell Mary the expected number of steps required to reach the KEY?
输入
There are no more than 70 test cases.
In each case , first Input a positive integer n(0<n<45), which means the layer of the maze, then Input five real number a, b, c, d, e. (0<=a,b,c,d,e<=1, a+b=1, c+d+e=1).
The input is terminated with 0. This test case is not to be processed.
输出
Please calculate the expected number of steps required to reach the KEY room, there are 2 digits after the decimal point.
样例输入
3
0.3 0.7
0.1 0.3 0.6
0
样例输出
3.41
思路
概率dp问题
dp [ i ] [ j ] 代表第 i 行第 j 个数所需要的步数
转移方程:
第n行: dp [ n ] [ i ] = dp [ n ] [ i - 1 ] + 1;
其他行:
如果位于左边界 dp [ i ] [ j ] = dp [ i + 1 ] [ j ] * a + dp [ i + 1 ] [ j + 1 ] * b + 1;
否则 dp [ i ] [ j ] = dp [ i + 1 ] [ j ] * c + dp [ i + 1 ] [ j + 1 ] * d + dp [ i ] [ j - 1 ] * e + 1;
(这是我做的第一个关于概率dp 的问题吧,拿来纪念一下( * ^ ▽ ^ * ))
代码
#include<iostream>
#include<string>
#include<map>
#include<set>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<stack>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define best 131
#define INF 0x3f3f3f3f
#define ls p<<1
#define rs p<<1|1
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double eps=1e-5;
const double pai=acos(-1.0);
const int N=1e5;
const int maxn=1e6+10;
double dp[50][50];
int main( )
{
int n;
double a,b,c,d,e;
while(~scanf("%d",&n))
{
if(n==0) break;
scanf("%lf%lf%lf%lf%lf",&a,&b,&c,&d,&e);
dp[n][1]=0;
for(int i=2;i<=n;i++)
{
dp[n][i]=dp[n][i-1]+1;
}
for(int i=n-1;i>=1;i--)
{
for(int j=1;j<=i;j++)
{
if(j==1) dp[i][j]=dp[i+1][j]*a+dp[i+1][j+1]*b+1;
else dp[i][j]=dp[i+1][j]*c+dp[i+1][j+1]*d+dp[i][j-1]*e+1;
}
}
printf("%.2f\n",dp[1][1]);
}
return 0;
}