poj 3744 Scout YYF I(矩陣快速冪+概率dp)

Scout YYF I
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 4569   Accepted: 1195

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
 
 
題解詳見:http://www.cnblogs.com/kuangbin/archive/2012/10/02/2710586.html
 
AC代碼:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <cmath>
#include <algorithm>
#define ll long long

using namespace std;

const int INF = 1e9;
const int maxn = 1000005;
const int mod = 100000000;

int n;
double p;
int mine[15];
struct Mat{
    double mat[2][2];
    void zero(){
        memset(mat, 0, sizeof(mat));
    }
    void unit(){
        zero();
        for(int i = 0; i < 2; i++) mat[i][i] = 1;
    }
}A, T;
Mat operator * (const Mat &a, const Mat & b){
    Mat tmp;
    for(int i = 0; i < 2; i++)
    for(int j = 0; j < 2; j++)
    {
        double sum = 0;
        for(int k = 0; k < 2; k++)
        sum += a.mat[i][k] * b.mat[k][j];
        tmp.mat[i][j] = sum;
    }
    return tmp;
}
Mat operator ^ (Mat x, int m){
    Mat tmp;
    tmp.unit();
    while(m)
    {
        if(m & 1) tmp = tmp * x;
        x = x * x;
        m >>= 1;
    }
    return tmp;
}
void init(){
    T.zero();
    T.mat[0][0] = p, T.mat[0][1] = 1 - p, T.mat[1][0] = 1;

}
int main()
{
    while(~scanf("%d%lf", &n, &p))
    {
        init();
        for(int i = 0; i < n; i++)
        scanf("%d", &mine[i]);
        sort(mine, mine + n);
        double ans = 1;
        Mat tmp = T ^ (mine[0] - 1);
        ans *= (1 - tmp.mat[0][0]);
        for(int i = 1; i < n; i++)
        {
            if(mine[i] == mine[i - 1]) continue;
            tmp = T ^ (mine[i] - mine[i - 1] - 1);
            ans *= (1 - tmp.mat[0][0]);
        }
        printf("%.7f\n", ans);
    }
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章