(概率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.

题意为一条路上分布着炸弹,主角有p的概率走一步,1-p的概率跳两步,刚开始位于1位置,给出每个炸弹的位置,问主角有多少概率存活
状态转移方程很简单dp[i]=p*dp[i-1]+(1-p)*dp[i-2],但是炸弹的位置十分大(1e8),考虑使用矩阵快速幂优化
考虑反向思考,我们记录在每个炸弹存活下来的概率相乘即可,每次从上一个炸弹的位置+1到这颗炸弹的概率算出来后用1减去相乘。

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
const int maxn = 100000000 + 5;
double pb;
struct Matrix {
    double a[4][4];
    int r, c;
};
Matrix multi(Matrix x, Matrix y) {
    Matrix ans;
    for (register int i = 0; i < x.r; i++) {
        for (register int j = 0; j < y.c; j++) {
            ans.a[i][j] = 0;
            for (register int k = 0; k < x.c; k++)
                ans.a[i][j] = ans.a[i][j] + x.a[i][k] * y.a[k][j];
        }
    }
    ans.r = x.r;
    ans.c = y.c;
    return ans;
}
double MatQP(int l) {
    Matrix p, q;
    memset(p.a, 0.0, sizeof(p.a));
    p.a[0][0] = pb, p.a[0][1] = 1.0, p.a[1][0] = 1.0 - pb, p.a[1][1] = 0.0;
    p.c = p.r = 2;
    q.a[0][0] = 1.0, q.a[0][1] = 0.0;
    q.r = 1, q.c = 2;
    while (l) {
        if (l & 1) q = multi(q, p);
        l >>= 1;
        p = multi(p, p);
    }
    return q.a[0][0];
}
int main()
{
    int n, stp;
    while(~scanf("%d%lf", &n, &pb)) {
        vector<int> cal(n + 1);
        for(int i = 1; i <= n; ++i)
            scanf("%d", &cal[i]);
        sort(cal.begin(), cal.end());
        double ans = 1.0;
        for(int i = 1; i <= n; i++)
            ans *= 1 - MatQP(cal[i] - cal[i - 1] - 1);
        printf("%.7f\n", ans);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值