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);
}
}