Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8286 | Accepted: 2440 |
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
题意:
你在一条布满地雷的道路上,开始在坐标1。每次有概率P向前走一步,有概率1-P向前走两步。道中路某几个点上会有地雷,问你安全通过的概率。地雷数N<=10,坐标范围在100000000内。
假设dp[i]表示安全走到i点的概率,那么dp[i]=P*dp[i-1]+(1-P)*dp[i-2]。很简单的一个转移,但是坐标范围太大了。直接递推爆内存,而且肯定也会超时。
我们换一个思路,假设x[i]表示第i个地雷的坐标。对于任何两个地雷x[i-1]+1~~x[i]之间,只会有一个地雷,那就是x[i]。我们安全通过该段的概率等于1 -踩到x[i]的概率。为什么可以这样呢。
我们前x[i]-1个位置看成一个位置。下一个位置只有两种可能。1.走到x[i]。2.走到x[i]+1。所以安全出来的概率就为1-踩到x[i]的概率。
也就是说,我们将n个地雷分成n段分别处理。每次都可以得到一个安全通过某一段的概率,最后将这些概率乘起来就是答案了。
由于数据比较大。
于是我们用矩阵来优化一下。
我们为这个dp[i]=P*dp[i-1]+(1-P)*dp[i-2]构造一个矩阵
| P ,1-P |
| 1 , 0 |
那么dp[n]就是该矩阵N次方后的第v[0,0]个元素。
因为。
|dp[n] | |p 1-p|^n-1 |dp[1]|
= *
|dp[n-1]| |1 0| |dp[0]|
而dp[1]=p。dp[0]=1。所以相当于矩阵的N次方去v[0,0]。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
struct node
{
double matrix[2][2];
node() {}
node(double a, double b, double c, double d)
{
matrix[0][0] = a;
matrix[0][1] = b;
matrix[1][0] = c;
matrix[1][1] = d;
}
};
node mul(node p, node q)
{
node t = node(0, 0, 0, 0);
for(int i = 0; i < 2; i++)
for(int j = 0; j < 2; j++)
for(int k = 0; k < 2; k++)
t.matrix[i][j] += p.matrix[i][k]*q.matrix[k][j];
return t;
}
node quick_matrix(node p, int k)
{
node q = node(1, 0, 0, 1);
while(k)
{
if(k&1) q = mul(q, p);
p = mul(p, p);
k >>= 1;
}
return q;
}
int main()
{
int n, a[20];
double p;
while(~scanf("%d%lf", &n, &p))
{
memset(a, 0, sizeof(a));
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
sort(a+1, a+1+n);
double ans = 1.0;
node init;
init.matrix[0][0] = p;
init.matrix[0][1] = 1-p;
init.matrix[1][0] = 1;
init.matrix[1][1] = 0;
for(int i = 1; i <= n; i++)
{
if(a[i]-a[i-1] == 0) continue;
node t = quick_matrix(init, a[i]-a[i-1]-1);
ans *= (1-t.matrix[0][0]);
}
printf("%.7f\n", ans);
}
return 0;
}