UVa--11181 Probability|Given(math)

来源:互联网 发布:淘宝店商品下架上架 编辑:程序博客网 时间:2024/05/18 00:19

UVa 11181

题意

n个人去超市逛,其中第i个人买东西的概率为Pi,已知有r个人买了东西,计算每个人实际买了东西的概率。
1<=n<=20, 0<=r<=n

题解

实际上这是计算条件概率:P(Ei|E)=P(EiE)P(E)
其中 P(Ei)表示第i个人买东西的概率,P(E)r个人买了东西的概率。
枚举所有的情况,共有Crn种,对这些情况下的概率进行累加。

#include <bits/stdc++.h>using namespace std;#define foreach(i, a, b) for(int i = a; i < b; ++i)const int maxn = 20 + 5;int n, r, buy[maxn];double p[maxn], sum[maxn];void dfs(int d, int c, double prob){    if(c > r || d - c > n - r) return;    if(d == n)    {        sum[n] += prob;        foreach(i, 0, n) if(buy[i])                sum[i] += prob;        return;    }    buy[d] = 0;    dfs(d + 1, c, prob * (1 - p[d]));    buy[d] = 1;    dfs(d + 1, c + 1, prob * p[d]);}int main(){    #ifdef LOCAL    freopen("data.in", "r", stdin);    #endif // LOCAL    int kcase = 1;    while(cin >> n >> r && n)    {        memset(buy, 0, sizeof(buy));        memset(sum, 0, sizeof(sum));        foreach(i, 0, n) cin >> p[i];        dfs(0, 0, 1.0);        printf("Case %d:\n", kcase++);        foreach(i, 0, n) printf("%.6f\n", sum[i] / sum[n]);    }    return 0;}
0 0