Description
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
Note there is at most one card in a bag of snacks. And it is possible that there is nothing in the bag.
Output
You will get accepted if the difference between your answer and the standard answer is no more that 10^-4.
題意:
每天你喫一包零食,零食中可能會出現一張收集卡片,卡片共N張,第I張出現的概率爲Pi,ΣPi<=1,保證一包零食中最多隻有一張卡片(可能沒有),問收集完所有卡片的期望天數。
範圍:
N<=20
解法:
N爲20,很容易發現需要狀壓,然後進行概率DP求解。
設DP[state]表示當前已收集狀態爲state的卡片,收集剩下的卡片的期望天數爲DP[state],顯然,邊界爲DP[(1<<n)-1]=0,目標爲DP[0]
枚舉當天打開的卡片爲K,如果K是已經得到過的,記這部分的概率和爲P0
轉移方程: DP[state] = ( Σ(DP[ state | (1<<x) ] * Px) +1 )/ (1-P0) 這裏的x表示當前狀態沒有得到過的卡片標號,之所以除以1-P0,是因爲移項的結果
代碼:
實現使用了記憶化搜索
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<iostream>
#include<stdlib.h>
#include<set>
#include<map>
#include<queue>
#include<vector>
#include<bitset>
#pragma comment(linker, "/STACK:1024000000,1024000000")
template <class T>
bool scanff(T &ret){ //Faster Input
char c; int sgn; T bit=0.1;
if(c=getchar(),c==EOF) return 0;
while(c!='-'&&c!='.'&&(c<'0'||c>'9')) c=getchar();
sgn=(c=='-')?-1:1;
ret=(c=='-')?0:(c-'0');
while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0');
if(c==' '||c=='\n'){ ret*=sgn; return 1; }
while(c=getchar(),c>='0'&&c<='9') ret+=(c-'0')*bit,bit/=10;
ret*=sgn;
return 1;
}
#define inf 1073741823
#define llinf 4611686018427387903LL
#define PI acos(-1.0)
#define lth (th<<1)
#define rth (th<<1|1)
#define rep(i,a,b) for(int i=int(a);i<=int(b);i++)
#define drep(i,a,b) for(int i=int(a);i>=int(b);i--)
#define gson(i,root) for(int i=ptx[root];~i;i=ed[i].next)
#define tdata int testnum;scanff(testnum);for(int cas=1;cas<=testnum;cas++)
#define mem(x,val) memset(x,val,sizeof(x))
#define mkp(a,b) make_pair(a,b)
#define findx(x) lower_bound(b+1,b+1+bn,x)-b
#define pb(x) push_back(x)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define lowbit(x) (x&(-x))
#define NN 100100
int n,tot;
double p[111];
double dp[1080000];
bool vis[1080000];
double dfs(int state){
if(state==tot)return 0;
if(vis[state])return dp[state];
vis[state]=1;
double rp=1.0;
dp[state]=1.0;
rep(i,0,n-1){
if((state&(1<<i))==0){
rp-=p[i];
dp[state]+=p[i]*dfs(state|(1<<i));
}
}
dp[state]/=(1.0-rp);
return dp[state];
}
int main(){
while(scanf("%d",&n)!=EOF){
rep(i,0,n-1)scanff(p[i]);
tot=(1<<n)-1;
rep(i,0,tot)vis[i]=0;
double ans=dfs(0);
printf("%.8lf\n",ans);
}
return 0;
}