Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5466 | Accepted: 1510 |
Description
Input
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
Sample Input
1 0.5 2 2 0.5 2 4
Sample Output
0.5000000 0.2500000
Source
这是一道比较经典的矩阵快速幂优化概率dp的题。给出了n个含有雷的位置。我们不能直接对位置进行概率dp,因为范围比较大,所以可以对n段分别计算,不断叠加。从而求出最终的概率。在这个过程中用矩阵快速幂来优化。该概率dp的状态转移方程比较好写。
参考代码:
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<ctime>
#include<cstdlib>
#include<iomanip>
#include<utility>
#define pb push_back
#define mp make_pair
#define CLR(x) memset(x,0,sizeof(x))
#define _CLR(x) memset(x,-1,sizeof(x))
#define REP(i,n) for(int i=0;i<n;i++)
#define Debug(x) cout<<#x<<"="<<x<<" "<<endl
#define REP(i,l,r) for(int i=l;i<=r;i++)
#define rep(i,l,r) for(int i=l;i<r;i++)
#define RREP(i,l,r) for(int i=l;i>=r;i--)
#define rrep(i,l,r) for(int i=1;i>r;i--)
#define read(x) scanf("%d",&x)
#define put(x) printf("%d\n",x)
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<11
using namespace std;
int n,a[20],dp[20];
double p;
struct mat
{
double d[2][2];
} A,B,E;
mat multi(mat a,mat b)
{
mat ans;
rep(i,0,2)
{
rep(j,0,2)
{
ans.d[i][j]=0.0;
rep(k,0,2)
if(a.d[i][k]>0&&b.d[k][j]>0)
ans.d[i][j]+=a.d[i][k]*b.d[k][j];
}
}
return ans;
}
mat quickmulti(mat a,int n)
{
mat ans=E;
while(n)
{
if(n&1) ans=multi(ans,a);
a=multi(a,a);
n>>=1;
}
return ans;
}
int main()
{
E.d[0][0]=E.d[1][1]=1;
E.d[0][1]=E.d[1][0]=0;
while(~scanf("%d%lf",&n,&p))
{
REP(i,1,n)
read(a[i]);
sort(a+1,a+n+1); //一定要对数组进行排序,因为雷区的位置不是从小到大排列的
A.d[0][0]=p,A.d[0][1]=1-p;
A.d[1][0]=1,A.d[1][1]=0;
B.d[0][0]=1,B.d[0][1]=B.d[1][0]=B.d[1][1]=0;
REP(i,1,n)
{
mat ans;
if(i==1)
{
ans=quickmulti(A,a[i]-1);
ans=multi(ans,B);
double p1=ans.d[1][0]*(1-p);
double p2=p1*p;
B.d[0][0]=p2,B.d[1][0]=p1;
}
else
{
if(a[i]-a[i-1]>=2) //要区分下一个雷区和当前雷区的位置关系,防止出现负数
{
ans=quickmulti(A,a[i]-a[i-1]-2);
ans=multi(ans,B);
double p1=ans.d[1][0]*(1-p);
double p2=p1*p;
B.d[0][0]=p2,B.d[1][0]=p1;
}
else //两个雷区连在一起,则肯定出不去,可以直接break
{
B.d[0][0]=B.d[1][0]=0;
break;
}
}
}
printf("%.7f\n",B.d[1][0]);
}
}