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.
InputThe 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.OutputOutput 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 种卡片,买一包零食最多有一张,可能没有,然后给出每种卡片的出现概率。想要每种都收集至少一张,问需要买的零食包数期望
题解:用dp做,用数字的二进制来表示状态,例如,4 种卡片的话 1110 表示 2-4 卡片至少有一种,第 1 种没有的情况
那么: dp[i] = SUM( pk * dp[i+k] ) + ( 1 - SUM(pk) ) * dp[i] + 1 (设 k 指的是缺少的卡片,pk 是获得这种卡片的概率)
即 dp[i] = ( SUM( pk * dp[i+k] ) + 1 ) / SUM(pk)
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 using namespace std; 5 6 const int MAXN = (1<<20)+10; 7 int n; 8 double p[25]; 9 double dp[MAXN]; 10 11 int main() 12 { 13 while(scanf("%d",&n)!=EOF) 14 { 15 for (int i=0;i<n;i++) 16 scanf("%lf",&p[i]); 17 18 int mmm = (1<<n)-1; //二进制为 n 个 1 19 dp[mmm]=0; 20 for (int i=mmm-1;i>=0;i--) //所有情况都遍历到 21 { 22 double all_p=0; 23 dp[i]=1; 24 for (int j=0;j<n;j++) 25 { 26 if ( (i&(1<<j))==0 ) //第 j 种卡片没有 27 { 28 dp[i]+=p[j]*dp[i+(1<<j)]; //dp [i+(1<<j)] 肯定赋过值了 29 all_p+=p[j]; 30 } 31 } 32 dp[i]/=all_p; 33 } 34 printf("%lf ",dp[0]); 35 } 36 }