POJ 3744 Scout YYF I Scout YYF I (递推+矩阵快速幂)

题意

有n个地方有地雷,初始站在1处,有p的概率往前走1步,1-p的概率往前走2步,求安全通过的概率。

思路

首先我们能想到的是直接递推即 dp[i]=pdp[i1]+(1p)dp[i2] 然后矩阵快速幂加速一下,但是这样做中间的地雷很难处理。
因为n很小我们就分段求,对每一个地雷求从前一个地雷到通过的概率,比如求通过第x个地雷的概率就是从 dp[x1]+1dp[x]+1 的概率,因为只有一步和两步,这个概率直接 1dp[x] 就可以了。
矩阵就是经典的斐波那契递推矩阵。

代码

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define LL long long
#define Lowbit(x) ((x)&(-x))
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1|1
#define MP(a, b) make_pair(a, b)
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const int maxn = 1e5 + 7;
const double eps = 1e-8;
const double PI = acos(-1.0);
int d = 2;
struct Matrix
{
    double a[100][100];
    Matrix()
    {
        memset(a, 0, sizeof(a));
    }
    void init()
    {
        for (int i = 0; i < d; i++) a[i][i] = 1;
    }
    Matrix operator * (const Matrix &B)const
    {
        Matrix C;
        for(int i = 0; i < d; i++)
            for(int j = 0; j < d; j++)
                for(int k = 0; k < d; k++)
                    C.a[i][j] = C.a[i][j] + a[i][k] * B.a[k][j];
        return C;
    }
    Matrix operator ^ (const int &t)const
    {
        Matrix res, A = (*this);
        res.init();
        int p = t;
        while (p)
        {
            if (p & 1) res = res * A;
            A = A * A;
            p >>= 1;
        }
        return res;
    }
    void print()
    {
        for (int i = 0; i < d; i++)
        {
            for (int j = 0; j < d; j++)
                printf("%-3d", a[i][j]);
            printf("\n");
        }
    }
};

int x[12];

int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int n;
    double p;
    while (scanf("%d%lf", &n, &p) != EOF)
    {
        x[0] = 0;
        for (int i = 1; i <= n; i++)
            scanf("%d", &x[i]);
        sort(x, x + n + 1);
        Matrix A, B;
        A.a[0][0] = p, A.a[0][1] = 1 - p;
        A.a[1][0] = 1, A.a[1][1] = 0;
        B.a[0][0] = 1;
        B.a[1][0] = 0;
        double ans = 1;
        for (int i = 1; i <= n; i++)
        {
            if (x[i] == x[i-1]) continue;
            Matrix temp = A;
            temp = temp ^ (x[i] - x[i-1]);
            temp = temp * B;
            ans *= (1 - temp.a[1][0]);
        }
        printf("%.7f\n", ans);
    }
    return 0;
}

你可能感兴趣的:(poj)