POJ 3744 概率dp+矩陣

life4711發表於2014-10-13

http://poj.org/problem?id=3744

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
在一條路(數軸)上有n個地雷,一人從1開始出發, 每走一步,有兩種情況:步子為1的概率為p;步子為2的概率為1-p。求能安全通過這條路的概率是多少?

解題思路:這是一道概率dp+矩陣的題,dp[i]=dp[i-1]*p+dp[i-2]*(1-p);這個題的資料範圍太大,中間又有地雷間隔,所以是不能直接跑的。我們依據地雷的位置把要求的概率看做n段來求:1~a[0],a[0]+1~a[1],,,,,,,a[n-2]+1~a[n-1].每一段的最後一個數為地雷的位置,這樣我們求出每個dp[  a[x] ]  的值,最後把所有的1-a[x] 相乘即為答案。對於每段我們用矩陣來做:                       

                            

值得一提的是:我們把初始矩陣直接看成:a[1]=1,a[0]=1;這樣做起來方便的多

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;

struct Matrix
{
    double m[2][2];
};

Matrix I={1,0,0,1};

Matrix mult_matrix(Matrix a,Matrix b)
{
    Matrix c;
    for(int i=0;i<2;i++)
       for(int j=0;j<2;j++)
       {
           c.m[i][j]=0;
           for(int k=0;k<2;k++)
              c.m[i][j]+=a.m[i][k]*b.m[k][j];
       }
    return c;
}

Matrix quick_mod(Matrix a,int n)
{
    Matrix c=I;
    while(n)
    {
        if(n&1)
            c=mult_matrix(c,a);
        a=mult_matrix(a,a);
        n>>=1;
    }
    return c;
}

int a[15],n;
double p;

int main()
{
    while(~scanf("%d%lf",&n,&p))
    {
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        sort(a,a+n);//順序
        double ans=1.0;
        Matrix A={p,1-p,1,0};//初始化轉移矩陣
        Matrix B=quick_mod(A,a[0]-1);
        ans*=(1-B.m[0][0]);
        for(int i=1;i<n;i++)
        {
            Matrix B=quick_mod(A,a[i]-a[i-1]-1);
            ans*=(1-B.m[0][0]);
        }
        printf("%.7lf\n",ans);
    }
    return 0;
}


相關文章