Card Collector(概率期望+容斥原理+状压)

In your childhood, do you crazy for collecting the beautiful cards in the snacks? They said that, for example, if you collect all the 108 people in the famous novel Water Margin, you will win an amazing award. 

As a smart boy, you notice that to win the award, you must buy much more snacks than it seems to be. To convince your friends not to waste money any more, you should find the expected number of snacks one should buy to collect a full suit of cards.

Input

The first line of each test case contains one integer N (1 <= N <= 20), indicating the number of different cards you need the collect. The second line contains N numbers p1, p2, ..., pN, (p1 + p2 + ... + pN <= 1), indicating the possibility of each card to appear in a bag of snacks. 

Note there is at most one card in a bag of snacks. And it is possible that there is nothing in the bag.

Output

Output one number for each test case, indicating the expected number of bags to buy to collect all the N different cards. 

You will get accepted if the difference between your answer and the standard answer is no more that 10^-4.

Sample Input

1
0.1
2
0.1 0.4

Sample Output

10.000
10.500

题目大意:

每包零食里有一张卡牌,总共有N种不同的卡牌,得到这N种卡牌的概率分别为P[i](1 <= i <= N)。

求收集到所有卡牌的期望是多少。

思路:

Pi表示得到第i张卡牌的概率,Ei表示得到第i张卡的期望。

假设现在有两张卡牌,由题意可知:

E1 = 1/P1,E2 = 1/P2,E12(表示肯定买到1或2其中一包的期望) = 1/(P1+P2)。

当我们计算E1和E2的时候,E12是重复计算了2次,应该减去一次。根据容斥定理可知:

E = E1 + E2 - E12。

同理,三张牌的时候:

E = E1 + E2 + E3 - E12 - E13 - E23 + E123。

以此类推,当计算期望中的各项的时候,如果该项为奇数项(奇数张卡的期望),则加上该项。

如果该项为偶数项2(偶数项卡的期望),则减去该项。

注意:误差不超过1e-4,别按照样例保留3位小数,多保留几位

#include<cstdio>
using namespace std;
double p[25];
int n;
double solve(){
	double ans=0;
	for(int i=1;i<(1<<n);i++){
		double sum=0;
		int cnt=0;
		for(int j=0;j<n;j++){
			if((1<<j)&i){
				cnt++;
				sum+=p[j+1];
			}
		}
		if(cnt&1) ans+=1.0/sum;
		else ans-=1.0/sum;
	}
	return ans;
}
int main(){
	while(~scanf("%d",&n)){
		for(int i=1;i<=n;i++)
		scanf("%lf",&p[i]);
		printf("%.6f\n",solve());
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_42936517/article/details/87931146