POJ3744 Scout YYF I (矩阵优化的概率DP)

Scout YYF I
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 一位童子兵要穿过一条路,路上有些地方放着地雷。这位童子兵非常好玩,走路一蹦一跳的。
每次他在 i 位置有 p 的概率走一步到 i+1 ,或者 (1-p) 的概率跳一步到 i+2。童子兵初始在1位置,求他安全通过这条道路的概率。
以所在位置为状态,dp[i] 表示在位置 i 的安全的概率。
dp[i] = p * dp[i-1] + (1 - p) * dp[i-2]; // i 位置没有地雷
但是题目数据的范围是 10^8 这样dp的话会 TLE。
想想可以用矩阵快速幂优化。简单推出矩阵是
|p 1-p| * |dp[i]   | = |dp[i+1]|
|1 0    |   |dp[i-1]|    |dp[i]     |
而这时地雷位置是不满足这个矩阵的,因此我们得对地雷位置进行特判。而两个地雷中间的位置可以用快速幂优化。
假设 k 位置放有地雷,,我们可以得到 dp[k+1] = dp[k-1] * (1 - p);
对于炸弹位置为 a[i] 和 a[i+1] 之间的数,知道 dp[a[i]+1] 后可以推出
POJ3744 Scout YYF I (矩阵优化的概率DP)
(视0位置有颗地雷,有地雷的位置的dp值为0)
于是我们可以对两个前后两个地雷之间用快速幂优化,并最终得到答案dp[max(a[i])+1];
转自:http://blog.csdn.net/xuelanghu407/article/details/47172759
 #include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
using namespace std; int n;double p;
int x[]; struct Node{double mat[][];};
Node mul(Node a,Node b)
{
Node res;
for(int i=;i<;i++)
for(int j=;j<;j++)
{
res.mat[i][j]=;
for(int k=;k<;k++) res.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
}
return res;
}
Node pow_M(Node a,int n)
{
Node res;
memset(res.mat,,sizeof(res.mat));
for(int i=;i<;i++)
res.mat[i][i]=;
Node temp=a;
while(n)
{
if(n&)res=mul(res,temp);
temp=mul(temp,temp);
n>>=;
}
return res;
}
int main()
{
while(~scanf("%d%lf",&n,&p))
{
for(int i=;i<n;i++)
scanf("%d",&x[i]);
sort(x,x+n);
double ans=;
Node tt;
tt.mat[][]=p;
tt.mat[][]=-p;
tt.mat[][]=;
tt.mat[][]=;
Node temp; temp=pow_M(tt,x[]-);
ans*=(-temp.mat[][]); for(int i=;i<n;i++)
{
if(x[i]==x[i-])continue;
temp=pow_M(tt,x[i]-x[i-]-);
ans*=(-temp.mat[][]);
}
printf("%.7f\n",ans);
}
}
 
上一篇:poj3744 Scout YYF I[概率dp+矩阵优化]


下一篇:[Poj3744]Scout YYF I (概率dp + 矩阵乘法)