E(\max_{i\in S}a_i)=\sum_{T\subseteq S,T\ne \varnothing}(-1)^{|T|+1}E(\min_{i\in T}a_i)
**[P3175 [HAOI2015] 按位或](https://www.luogu.com.cn/problem/P3175)**
变成 $2^n-1$ 的时间就是二进制下最后变成 $1$ 的那一位的时间,其实不太好求,于是可以用 min-max 的式子转化为求最先出现的时间,这个就可以直接用 $\frac{1}{1-P_{U/T}}$ 得到,其中 $P_T=\sum_{i\subseteq T}p_i$。
枚举复杂度还是会炸,但发现这就是个集合并,直接高位前缀和就行了。复杂度 $O(n2^n)$。
```cpp
#include <bits/stdc++.h>
#define pc(i) __builtin_popcount(i)
using namespace std;
const int N = 20;
const double eps = 1e-10;
double f[1 << N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n, s; cin >> n; n = 1 << n;
for (int i = 0; i < n; i++) cin >> f[i];
for (int i = 1; i < n; i <<= 1)
for (int j = 0; j < n; j++)
if (j & i) f[j] += f[j ^ i];
double ans = 0;
for (int i = 1; i < n; i++)
if (1 - f[n - 1 ^ i] > eps)
ans += ((pc(i) & 1) ? 1 : -1) / (1 - f[n - 1 ^ i]);
if (ans < eps) cout << "INF\n";
else printf("%.10lf\n", ans);
return 0;
}
```
**[P4707 重返现世](https://www.luogu.com.cn/problem/P4707)**
最好求的其实是 $E_{\min}$(虽然这不代表着 $\operatorname{kth} E_{\min}$ 好求),所以先令 $k'=n-k+1$ 转换为 $E_{\max}$,然后再用扩展的 min-max 式子转化为 $E_{\min}$。
但是上一题可以直接转化是因为长度很小,这题怎么也不像可以枚举子集的样子。先写出式子:
$$ans=\sum_{T\subseteq S,|T|\ge k'}(-1)^{|T|-k'}\dbinom{|T|-1}{k'-1}\frac{m}{P_T}$$
其中 $P_T=\sum_{i\in T}p_i$。
但是会发现这个的 $\frac{m}{P_T}$ 只需要算一个线性的 $P_T$,因此可以考虑 dp。设 $f_{i,j,x}$ 表示前 $i$ 个数,当前 $|T|=j,p_T=x$ 的方案数,直接做是 $O(n^2m)$ 的。
注意到题目里还有一个 $n-k\le 10$ 没用到,发现系数有递推式:
$$(-1)^{|T|-k'}\dbinom{|T|-1}{k'-1}=(-1)^{|T|-k'}\dbinom{|T|-2}{k'-2}-(-1)^{|T|-k'+1}\dbinom{|T|-2}{k'-1}$$
于是可以把 $|T|$ 从状态里扔掉然后记一个 $j=k'$,这样就有:
$$f_{i,j,x}=f_{i-1,j,x}+f_{i-1,j-1,x-p_i}-f_{i-1,j,x-p_i}$$
(这里可能会有点怪,类似[这题](http://218.5.5.242:9019/problem/185588541))
这样总状态数就只有 $O(nmk')$ 了。初始是 $f_{0,0,0}=1$(可能直接带进去式子没有意义的,但想过去相当于是“第 $0$ 小”)。
```cpp
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int P = 998244353;
inline int qpow(int a, int b = P - 2) {
int res = 1;
while (b) {
if (b & 1) res = res * a % P;
a = a * a % P, b >>= 1;
} return res;
}
const int N = 1005, K = 15, M = 1e4 + 5;
int f[2][K][M], a[N];
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n, k, m; cin >> n >> k >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
k = n - k + 1; f[0][0][0] = 1;
for (int i = 1; i <= n; i++) {
int x = i & 1, y = x ^ 1;
memset(f[x], 0, sizeof(f[x]));
for (int j = 0; j <= k; j++)
for (int p = 0; p <= m; p++) {
f[x][j][p] = f[y][j][p]; if (p < a[i] || !j) continue;
(f[x][j][p] += P + f[y][j - 1][p - a[i]] - f[y][j][p - a[i]]) %= P;
}
}
int ans = 0;
for (int i = 0; i <= m; i++)
ans = (ans + f[n & 1][k][i] * qpow(i)) % P;
cout << ans * m % P << '\n';
return 0;
}
```
**练习**
- [P5643 [PKUWC2018] 随机游走](https://www.luogu.com.cn/problem/P5643)