地址:http://poj.org/problem?id=3744
Scout YYF I
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 4219 | Accepted: 1089 |
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
题意:YYF走地雷阵,他一次走一步的概率是p,走两步的概率是1-p,地雷一共有n个,其坐标在第二行依次给出。问安全通过的概率。
思路:动态转移方程式q[i]=q[i-1]*p+q[i-2]*(1-p).(感觉像递推之类的,这一步受前两步的影响)
由于地雷坐标范围过大,所以用矩阵优化。(没做过几道矩阵二分优化的题目,所以卡在这里了。虽然有思路,并且知道矩阵优化的原理,但是矩阵设不出。要多练些矩阵的题目)
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
double p[2][2];
};
node juzhenc(node a,node b) //矩阵相乘
{
node c;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
{
c.p[i][j]=0;
for(int k=0;k<2;k++)
c.p[i][j]+=a.p[i][k]*b.p[k][j];
}
return c;
}
node getans(node a,node b,int k) //二分优化
{
while(k)
{
if(k&1) b=juzhenc(a,b);
a=juzhenc(a,a);
k>>=1;
}
return b;
}
int main()
{
int n;
double p;
while(scanf("%d%lf",&n,&p)>0)
{
int mine[20]={0};
for(int i=0;i<n;i++)
scanf("%d",&mine[i]);
sort(mine,mine+n);
node a,b;
b.p[0][0]=1;b.p[0][1]=0;
b.p[1][0]=0;b.p[1][1]=0;
for(int i=0;i<n;i++)
{
a.p[0][0]=p;
a.p[0][1]=1-p;
a.p[1][0]=1;
a.p[1][1]=0;
if(!i) mine[i]--;
else mine[i]-=(mine[i-1]+1);
b=getans(a,b,mine[i]);
b.p[0][0]=0;
}
printf("%.7f\n",b.p[1][0]*(1-p)); //注意用%f
}
return 0;
}