1. 程式人生 > >Scout YYF I (矩陣優化)

Scout YYF I (矩陣優化)

Description

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.

Input

The input contains many test cases ended with EOF.
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

For each test case, output the probabilty in a single line with the precision to 7 digits after the decimal point.

Sample Input

1 0.5
2
2 0.5
2 4

Sample Output

0.5000000
0.2500000

題解

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define lowbit(x) (x&(-x))
#define ls(x) (x<<1)//儘量巨集定義吧,不太容易出錯 
#define rs(x) (x<<1|1)
using namespace std;
typedef long long ll;
struct Mar{
	double arr[3][3];
}e,st;	
int n;double p;
int val[20];

void init(){
	memset(st.arr,0,sizeof(st.arr));
	memset(e.arr,0,sizeof(e.arr));
	st.arr[1][1]=p,st.arr[1][2]=1-p;
	st.arr[2][1]=1;
	e.arr[1][1]=e.arr[2][2]=1;
}

Mar mul(Mar a,Mar b){
	Mar ans;
	for(int i=1;i<=2;i++){
		for(int j=1;j<=2;j++){
			ans.arr[i][j]=0;
			for(int k=1;k<=2;k++){
				ans.arr[i][j]+=a.arr[i][k]*b.arr[k][j];
			}
		}
	}
	return ans;
}

Mar pow(Mar st,int n){
	Mar ans=e;
	while(n){
		if(n&1)
			ans=mul(ans,st);
		st=mul(st,st);
		n/=2;
	}
	return ans;
}

int main()
{
	while(~scanf("%d %lf",&n,&p)){
		for(int i=1;i<=n;i++){
			scanf("%d",&val[i]); 
		}
		double ans=1;
		for(int i=1;i<=n;i++){
			if(val[i]==1||(i>1&&val[i]==val[i-1]+1)){
				ans=0;break;
			}
			else if(i==1){
				init();
				st=pow(st,val[i]-1);
				ans*=(1-st.arr[1][1]);
			}
			else{
				init();
				st=pow(st,val[i]-(val[i-1]+1));
				ans*=(1-st.arr[1][1]);
			}
		}
		printf("%.7f\n",ans);
	}
	return 0;
}