第五十八题 UVa 11181 Probability|Given

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

题目分析
条件概率:P(B|A)=P(A∩B)/P(A)
用样例解释就是:P(B)= 0.10.20.7+0.10.30.8+0.20.30.9
P(A∩B)=0.10.20.7+0.10.30.8。。
得到P(A|B)

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
double p[22],fac,Ans[22];
int n,r;
bool vis[22];
void DFS(int step,double sum,int cnt){
	if(cnt>r) return;
	if(step==n+1){
		if(cnt==r){
			fac+=sum;
			for(int i=1;i<=n;++i)
				if(vis[i]) Ans[i]+=sum;
		}
		return ;
	}
	vis[step]=true;
	DFS(step+1,sum*p[step],cnt+1);
	vis[step]=false;
	DFS(step+1,sum*(1-p[step]),cnt);
}

int Main(){
	scanf("%d%d",&n,&r);
	for(int i=1;i<=n;++i) scanf("%lf",&p[i]);
	DFS(1,1.0,0);
	for(int i=1;i<=n;++i) printf("%.3lf\n",Ans[i]/fac);
	return 0;
}
int Aptal_is_My_Son=Main();
int main(int argc,char *argv[]){ ; }
发布了732 篇原创文章 · 获赞 31 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/qq_35776409/article/details/104041648