uva 11181 DFS+概率计算

来源:互联网 发布:淘宝网伴娘礼服 编辑:程序博客网 时间:2024/05/01 16:52

N friends go to the local super market together. The probability of their buying something from the
market is p1, p2, p3, … , pN respectively. After their marketing is finished you are given the information
that exactly r of them has bought something and others have bought nothing. Given this information
you will have to find their individual buying probability.
Input
The input file contains at most 50 sets of inputs. The description of each set is given below:
First line of each set contains two integers N (1 ≤ N ≤ 20) and r (0 ≤ r ≤ N). Meaning of N and
r are given in the problem statement. Each of the next N lines contains one floating-point number pi
(0.1 < pi < 1) which actually denotes the buying probability of the i-th friend. All probability values
should have at most two digits after the decimal point.
Input is terminated by a case where the value of N and r is zero. This case should not be processes.
Output
For each line of input produce N +1 lines of output. First line contains the serial of output. Each of the
next N lines contains a floating-point number which denotes the buying probability of the i-th friend
given that exactly r has bought something. These values should have six digits after the decimal point.
Follow the exact format shown in output for sample input. Small precision errors will be allowed. For
reasonable precision level use double precision floating-point numbers.
Sample Input
3 2
0.10
0.20
0.30
5 1
0.10
0.10
0.10
0.10
0.10
0 0
Sample Output
Case 1:
0.413043
0.739130
0.847826
Case 2:
0.200000
0.200000
0.200000
0.200000
0.200000

题目大意:
N个朋友去买东西,给出每个人买了的概率,最终由R人买了,求每个人买了东西的概率。
以第一组数据为例:因为有两人买了,有三种情况 101 011 110 (1表示买了) 101 的概率为 p1*(1-p2)*p3 类推011 和110 得到三个概率。而第i个人买的概率就是包含了他买的情况的概率相加除以总的情况的概率相加
所以 DFS一下 记下每个ans【i】和tot 相除即可。

#include<stdio.h>#include<algorithm>#include<iostream>#include<cmath>#include<cstring>#include<vector>#include<queue>using namespace std;int N,R;int vis[21];double a[21],ans[21],tot;void dfs(int n,int k){    if(N-n<R-k)return ;    vis[n]=1;    if(k==R){        double t=1;        for(int i=1;i<=N;i++){            if(vis[i])t*=a[i];            else t*=(1-a[i]);        }        tot+=t;        for(int i=1;i<=N;i++){            if(vis[i])ans[i]+=t;        }    }    for(int i=n+1;i<=N;i++){        dfs(i,k+1);    }    vis[n]=0;}int main(){    int kase=0;    while(~scanf("%d%d",&N,&R),N||R){        memset(a,0,sizeof(a));        memset(ans,0,sizeof(ans));        tot=0;        for(int i=1;i<=N;i++){            scanf("%lf",a+i);        }        printf("Case %d:\n",++kase);        if(R==0){            for(int i=0;i<N;i++)                printf("0.000000\n");        }        else {            memset(vis,0,sizeof(vis));            dfs(0,0);            for(int i=1;i<=N;i++){                printf("%.6lf\n",ans[i]/tot);            }        }    }    return 0;}
0 0