【UVA 11181】(条件概率)
题链:https://cn.vjudge.net/problem/UVA-11181
题意
n个人去了超市,已知每个人买东西的概率为p[i],在已知有r个人买了东西的情况下,求实际上每个人买东西的概率
题解
设r个人买东西的时间为E
\[ans=p(i\;|\;E)=\frac{p(iE)}{p(E)}
\]
每个人买东西的概率是独立的,在一种r情况下,利用乘法原理即可。
多种r情况是互斥的,累加起来即可。
参考代码
import java.io.*;
import java.util.*;
public class Main {
static final int N=(int)5005;
static double p[]=new double[25];
static boolean vis[]=new boolean[25];
static int n,r;
static double sum[]=new double[25];
static void dfs(int step,int cnt,double res) {
if(step==n+2||cnt>r) return;
if(step==n+1&&cnt==r) {
sum[0]+=res;
for(int i=1;i<=n;i++) if(vis[i]) {
sum[i]+=res;
}
return;
}
vis[step]=false;
dfs(step+1,cnt,res*(1-p[step]));
vis[step]=true;
dfs(step+1,cnt+1,res*p[step]);
}
public static void main(String[] args) {
InputStream sys=System.in;
InputReader in=new InputReader(sys);
// Scanner sc=new Scanner(new InputStreamReader(sys));
PrintWriter out=new PrintWriter(System.out);
int T=1;
while(true) {
n=in.nextInt();r=in.nextInt();
if(n==0&&r==0) break;
for(int i=1;i<=n;i++) {
p[i]=in.nextDouble();
vis[i]=false;sum[i]=0;
}
sum[0]=0;
dfs(1,0,1);
StringBuffer ans=new StringBuffer();
for(int i=1;i<=n;i++) {
ans.append(String.format("%.6f\n", sum[i]/sum[0]));
}
out.println("Case "+(T++)+":");
out.print(ans);
out.flush();
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}