Scout YYF I
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5304 | Accepted: 1455 |
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].
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
题意:有一条布满N颗地雷的路径,从起点1开始。然后N个雷的位置。往前走一步的概率为P,往前走两步的概率为1-P、问能安全通过这条路径的概率是多大。
到达i位置的概率为:DP[i]=DP[i-2]*(1-P)+DP[i-1]*P
题解:分段计算概率,将N颗雷分解成N段路,N颗雷位置排好序a[0]-a[N-1].
第一段路径为1~a[0],
第二段路径为a[0]+1~a[1],依次类推。
然后将能安全经过这N条分解的路径的乘积即是答案。
安全经过第i条路径的概率(1-为正好走到地雷的位置的概率)
因为路径太长,只能用矩阵快速幂求解每个地雷位置的概率。当然起点位置设置为前一个地雷位置安全经过的下一个点概率为1.
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <queue>
#include <map>
#include <stack>
#include <list>
#include <vector>
#include <ctime>
#define LL __int64
#define eps 1e-8
#define pi acos(-1)
using namespace std;
struct Matrix{
double go[2][2];
Matrix operator *(const Matrix a){
Matrix res;
memset(res.go,0,sizeof(res.go));
for (int i=0;i<2;i++)
for (int j=0;j<2;j++)
for (int k=0;k<2;k++)
res.go[i][j]+=go[i][k]*a.go[k][j];
return res;
}
};
Matrix KSM(Matrix a,int k){
Matrix res;
memset(res.go,0,sizeof(res.go));
for (int i=0;i<2;i++)
res.go[i][i]=1;
Matrix temp=a;
while (k){
if (k&1) res=res*temp;
temp=temp*temp;
k>>=1;
}
return res;
}
int a[20];
int main(){
int n;
double p;
while (~scanf("%d%lf",&n,&p)){
for (int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
Matrix t;
t.go[0][0]=p;
t.go[0][1]=1-p;
t.go[1][0]=1;
t.go[1][1]=0;
double ans=1;
for (int i=0;i<n;i++){
Matrix temp;
if (i==0)
temp=KSM(t,a[0]-1);
else
temp=KSM(t,a[i]-a[i-1]-1);
ans*=(1-temp.go[0][0]);
}
printf("%.7f\n",ans);
}
return 0;
}