Scout YYF I
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 10125 Accepted: 2954
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
题意
一条路,有一个士兵在位置1,他有p的概率向前跳1步,1-p的概率向前跳两步,路上还有n颗地雷,士兵碰到地雷任务就会失败,求失败通过这条路完成任务的概率
思路
很容易想到若没有地雷士兵从一个坐标跳到另一个坐标的概率公式
即
a
n
=
p
a
n
−
1
+
(
1
−
p
)
a
n
−
2
a_{n}=pa_{n-1}+(1-p)a_{n-2}
an=pan−1+(1−p)an−2那么我们怎么处理地雷呢,我们可以这样考虑把每两个地雷之间单独拿出来算,即从地雷
x
+
1
x+1
x+1跳到地雷
y
y
y的概率因为求得是跳到地雷上的概率,那么跳过地雷到大
y
+
1
y+1
y+1的概率就是1-ans,一开始士兵位于1,我们可以认为在位置0上面有一颗地雷。又因为 地雷的范围为
[
1
,
100000000
]
[1, 100000000]
[1,100000000]递推公式得用矩阵快速幂优化一下,在位置1的概率为1,而在位置0的概率就为0,所以得到的概率就是
m
[
0
]
[
0
]
m[0][0]
m[0][0]
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#define MAX 2
using namespace std;
typedef struct
{
double m[MAX][MAX];
} Matrix;
Matrix P;
Matrix I= {1,0,0,1};
Matrix Matrixmul(Matrix a,Matrix b)
{
int i,j,k;
Matrix c;
for(i=0; i<MAX; i++)
for(j=0; j<MAX; j++)
{
c.m[i][j]=0;
for(k=0; k<MAX; k++)
{
c.m[i][j]+=(a.m[i][k]*b.m[k][j]);
}
}
return c;
}
Matrix quickpow(long long n)
{
Matrix m=P,b=I;
while(n>0)
{
if(n%2==1)
b=Matrixmul(b,m);
n=n/2;
m=Matrixmul(m,m);
}
return b;
}
int a[15];
int main()
{
int n;
double p;
while(scanf("%d%lf",&n,&p)!=EOF)
{
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
sort(a,a+n);
if(a[0]==1)
{
printf("%.7lf\n",0);
continue;
}
P.m[0][0]=p;
P.m[0][1]=1-p;
P.m[1][0]=1;
P.m[1][1]=0;
double ans=1;
Matrix A;
A=quickpow(a[0]-1);
ans=1-A.m[0][0];
for(int i=1; i<n; i++)
{
if(a[i]==a[i-1])continue;
A=quickpow(a[i]-a[i-1]-1);
ans*=(1-A.m[0][0]);
}
printf("%.7f\n",ans);
}
return 0;
}
注意的是这题得用**%.7f**