传送门
Scout YYF I
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 7221 Accepted: 2106
Description
YYF is a couragous scout. Now he is on a dangerous mission which is to penetrate into the enemy’s base. After overcoming a series difficulties, YYF is now at the start of enemy’s famous “mine road”. This is a very long road, on which there are numbers of mines. At first, YYF is at step one. For each step after that, YYF will walk one step with a probability of p, or jump two step with a probality of 1-p. Here is the task, given the place of each mine, please calculate the probality that YYF can go through the “mine road” safely.
Input
The input contains many test cases ended with EOF.
Each test case contains two lines.
The First line of each test case is N (1 ≤ N ≤ 10) and p (0.25 ≤ p ≤ 0.75) seperated by a single blank, standing for the number of mines and the probability to walk one step.
The Second line of each test case is N integer standing for the place of N mines. Each integer is in the range of [1, 100000000].
Output
For each test case, output the probabilty in a single line with the precision to 7 digits after the decimal point.
Sample Input
1 0.5
2
2 0.5
2 4
Sample Output
0.5000000
0.2500000
Source
POJ Monthly Contest - 2009.08.23, Simon
题目大意:
有一个雷区,这个雷区有 n 个雷,有一个人想安全的走过这个雷区,每次只能走一步或者是两步,走一步的概率就是 p, 两步的概率就是 1-p,让你求的就是这个人安全走过雷区的概率。
解题思路:
首先一看到这是一个关于概率的问题,那么我们可以想到这就可能是一个概率DP的问题,我们来分析一下。我们假设 DP[i]是安全走到 i 点的概率,那么我们可以这么想 如果要想安全走到 i 点,一定是安全走到 i-1 点在走一步,或者是安全走到 i-2点 在走两步,那么我们可以大恶道递推方程:
My Code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 2;
typedef struct
{
double mat[MAXN][MAXN];
} Matrix;
double p;
Matrix PP = {p, 1,
1-p,0,
};
Matrix I = {1, 0,
0, 1,
};
Matrix Mul_Matrix(Matrix a, Matrix b)
{
Matrix c;
for(int i=0; i<MAXN; i++)
{
for(int j=0; j<MAXN; j++)
{
c.mat[i][j] = 0;
for(int k=0; k<MAXN; k++)
c.mat[i][j] += a.mat[i][k] * b.mat[k][j];
}
}
return c;
}
Matrix quick_Matrix_Mod(int m)
{
Matrix ans = I, a = PP;
while(m)
{
if(m & 1)
ans = Mul_Matrix(ans, a);
m>>=1;
a = Mul_Matrix(a, a);
}
return ans;
}
int a[15];
int main()
{
int n;
a[0] = 0;
while(cin>>n>>p)
{
for(int i=1; i<=n; i++)
cin>>a[i];
sort(a+1, a+n+1);
PP.mat[0][0] = p;
PP.mat[0][1] = 1-p;
if(a[1] == 1)
{
printf("%.7lf\n",0.0);
continue;
}
double ans = 1.0;
Matrix ret = I;
int k=n+1;
for(int i=1; i<=n; i++)
{
if(a[i] == a[i-1])
continue;
if(a[i] == a[i-1]+1)///不加这句话会超时(在这种情况下一定是踩雷的)
{
k = i;
break;
}
ret = quick_Matrix_Mod(a[i]-a[i-1]-2);
///cout<<"ret.mat[0][0] == "<<ret.mat[0][0]<<endl;
ans *= (ret.mat[0][0])*(1-p);
}
if(k <= n)
printf("%.7lf\n",0.0);
else
printf("%.7lf\n",ans);
}
return 0;
}