HDU4336 Card Collector(期望 狀壓 MinMax容斥)
阿新 • • 發佈:2019-01-01
題意
\(N\)個物品,每次得到第\(i\)個物品的概率為\(p_i\),而且有可能什麼也得不到,問期望多少次能收集到全部\(N\)個物品
Sol
最直觀的做法是直接狀壓,設\(f[sta]\)表示已經獲得了\(sta\)這個集合裡的所有元素,距離全拿滿的期望,推一推式子直接轉移就好了
主程式程式碼:
int N; double a[MAXN], f[MAXN]; signed main() { // freopen("a.in", "r", stdin); while(scanf("%d", &N) != EOF) { memset(f, 0, sizeof(f)); double res = 1.0; for(int i = 0; i < N; i++) scanf("%lf", &a[i]), res -= a[i]; int Lim = (1 << N) - 1; for(int sta = Lim - 1; sta >= 0; sta--) { double now = 1 - res, sum = 0; for(int i = 0; i < N; i++) if(sta & (1 << i)) now -= a[i]; else sum += f[sta | (1 << i)] * a[i]; sum += 1.0; f[sta] = sum / now; } printf("%.4lf\n", f[0]); } return 0; }
另一種MinMax容斥的做法:
設\(max(s)\)為\(s\)集合中的最大元素,\(min(T)\)為集合\(T\)中的最小元素
那麼有\(E(max(s)) =\sum_{T \subseteq S} (-1)^{|T| + 1} E(min \{ T \})\)
這裡的\(E(max(S))\)顯然就是我們要求的答案
\(E(min \{ T\}) = \frac{1}{\sum_{i \in T} p_i}\)
直接dfs一波
#include<bits/stdc++.h> #define Pair pair<int, int> #define MP(x, y) make_pair(x, y) #define fi first #define se second //#define int long long #define LL long long #define Fin(x) {freopen(#x".in","r",stdin);} #define Fout(x) {freopen(#x".out","w",stdout);} using namespace std; const int MAXN = 2e6 + 10, mod = 1e9 + 7, INF = 1e9 + 10; const double eps = 1e-7; template <typename A, typename B> inline bool chmin(A &a, B b){if(a > b) {a = b; return 1;} return 0;} template <typename A, typename B> inline bool chmax(A &a, B b){if(a < b) {a = b; return 1;} return 0;} template <typename A, typename B> inline LL add(A x, B y) {if(x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y;} template <typename A, typename B> inline void add2(A &x, B y) {if(x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y);} template <typename A, typename B> inline LL mul(A x, B y) {return 1ll * x * y % mod;} template <typename A, typename B> inline void mul2(A &x, B y) {x = (1ll * x * y % mod + mod) % mod;} template <typename A> inline void debug(A a){cout << a << '\n';} template <typename A> inline LL sqr(A x){return 1ll * x * x;} inline int read() { char c = getchar(); int x = 0, f = 1; while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();} while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return x * f; } int N; double a[MAXN], ans; void dfs(int x, double p, int opt) { if(x == N) { if(p > eps) ans += opt / p; return ; } dfs(x + 1, p, opt); dfs(x + 1, p + a[x], -opt); } signed main() { // freopen("a.in", "r", stdin); while(scanf("%d", &N) != EOF) { for(int i = 0; i < N; i++) scanf("%lf", &a[i]); ans = 0; dfs(0, 0, -1); printf("%.4lf\n", ans); } return 0; }