ACMer去刷题吧 XDU1020

1.题目描述:点击打开链接

2.解题思路:本题利用概率dp解决。根据题意描述,我们可以定义d(i,j)表示前i道题做对j道的概率。那么根据全概率公式,可以得到如下递推式:

d(i,j)=d(i-1,j)*(1-p[i])+d(i-1,j-1)*p[i](0≤j≤i)

其中p[i]表示第i道题做对的概率。这样,得到所有的d值后,ans=sum{d(i,j)|k≤j≤n}

3.代码:

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;

#define N 1000+10
double p[N];
double d[N][N];
int n, k;

int main()
{
	//freopen("t.txt", "r", stdin);
	int T;
	scanf("%d", &T);
	while (T--)
	{
		scanf("%d%d", &n, &k);
		memset(p, 0, sizeof(p));
		memset(d, 0, sizeof(d));
		for (int i = 1; i <= n; i++)
			scanf("%lf", &p[i]);
		d[0][0] = 1.0;
		for (int i = 1; i <= n; i++)
		for (int j = 0; j <= i; j++)//注意,j一定要从0开始算起
		{
			d[i][j] = d[i - 1][j] * (1 - p[i]);
			if (j)d[i][j] += d[i - 1][j - 1] * p[i];
		}
		double ans = 0.0;
		for (int j = k; j <= n; j++)
			ans += d[n][j];
		printf("%.4lf\n", ans);
	}
	return 0;
}

你可能感兴趣的:(概率DP)