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