HDU4336 Card Collector(期望 状压 MinMax容斥)

时间:2022-04-18 02:12:20

题意

题目链接

\(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;
}