题目链接:http://poj.org/problem?id=3744
题意:一开始有一个人在1号点,他有p的概率向前走一步,有1-p的概率向前跳两步,然后有一些位置是地雷,不能走,问他可以成功穿越雷区的概率。
思路:划分区间求概率之积。一个区间只有一个地雷,这样这个区间就变成了,一开始在起点,然后跳过地雷的概率(跳过地雷后一定是在下一个区间的起点),f[i+2] = f[i]*(1-p)+f[i+1]*p。但是范围很大,只能用矩阵快速幂来转移。
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;
#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)
#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod %100000007
int n;
double p;
int point[12];
struct node
{
double a[2][2];
node(double x = 1 ,double y = 0,double c = 0,double d = 1) //单位矩阵
{
a[0][0] = x , a[0][1] = y;
a[1][0] = c , a[1][1] = d;
}
};
node multi( node & x , node & y )//矩阵乘法
{
node ans(0,0,0,0);
rep(i,0,1)
rep(j,0,1)
rep(k,0,1)
ans.a[i][j] += x.a[i][k]*y.a[k][j];
return ans;
}
double cal(int k) //计算转移矩阵的k次方,也就是走k步之后
{
if ( k < 0 ) return 0;
if ( k == 0 ) return 1;
node temp(0,1-p,1,p); //转移矩阵的1次方
node ans;
while( k )
{
if ( k & 1 )
ans = multi(ans,temp);
temp = multi(temp,temp);
k>>=1;
}
return ans.a[0][0]+p*ans.a[1][0];
}
int main()
{
while(~scanf("%d %lf",&n,&p))
{
rep(i,1,n) scanf("%d",&point[i]);
sort(point+1,point+1+n);
double ans = 1;
int st = 1;
rep(i,1,n)
{
ans *= cal( point[i]-st-1 )*(1-p); //每次从起点走到地雷的前一个位置,然后再跳过去。
st = point[i]+1; //下一个区间的起点
}
printf("%0.7f\n",ans);
}
return 0;
}