UVA11181 Probability|Given 条件概率

vjudge传送
条件概率典型例题。 对于第$i$个人,用条件概率公式$P(A|B)=frac{P(AB)}{P(B)}$.其中$P(A|B)$表示在$r$个人买东西的前提下,$i$买东西的概率,$P(AB)$表示总共有$r$个人买东西,且第$i$个人也买东西的概率,$P(B)$表示$r$个人买东西的概率。 因为$nleqslant 20$,所以可以直接$2^n$枚举所有可能情况,把对应的符合条件的概率加一块就好了。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<queue>
#include<assert.h>
#include<ctime>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
#define forE(i, x, y) for(int i = head[x], y; ~i && (y = e[i].to); i = e[i].nxt)
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 25;
In ll read()
{
	ll ans = 0;
	char ch = getchar(), las = ' ';
	while(!isdigit(ch)) las = ch, ch = getchar();
	while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
	if(las == '-') ans = -ans;
	return ans;
}
In void write(ll x)
{
	if(x < 0) x = -x, putchar('-');
	if(x >= 10) write(x / 10);
	putchar(x % 10 + '0');
}
In void MYFILE()
{
#ifndef mrclr
	freopen(".in", "r", stdin);
	freopen(".out", "w", stdout);
#endif
}

int n, m;
db a[maxn], ans[maxn];

In void solve()
{
	Mem(ans, 0);
	int N = 1 << n; db p = 0;
	for(int i = 0; i < N; ++i)
	{
		int cnt = 0;
		for(int j = 0; j < n; ++j) cnt += ((i >> j) & 1);
		if(cnt ^ m) continue;
		db num = 1;
		for(int j = 0; j < n; ++j)
			num *= ((i >> j) & 1) ? a[j + 1] : (1 - a[j + 1]);
		for(int j = 0; j < n; ++j)
			if((i >> j) & 1) ans[j + 1] += num;
		p += num;
	}
	for(int i = 1; i <= n; ++i) ans[i] = ans[i] / p;
}

int main()
{
//	MYFILE();
	int T = 0; 
	while(scanf("%d%d", &n, &m) && (n | m))
	{
		for(int i = 1; i <= n; ++i) scanf("%lf", &a[i]);
		solve();
		printf("Case %d:
", ++T);
		for(int i = 1; i <= n; ++i) printf("%lf
", ans[i]);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/mrclr/p/14601363.html