0%

子集枚举(SOS)

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//iterative version
for(int mask = 0; mask < (1<<N); ++mask) {
dp[mask][-1] = A[mask];
//handle base case separately (leaf states)
for(int i = 0;i < N; ++i){
if(mask & (1<<i))
dp[mask][i] = dp[mask][i-1] + dp[mask^(1<<i)][i-1];
else
dp[mask][i] = dp[mask][i-1];
}
F[mask] = dp[mask][N-1];
}

//memory optimized, super easy to code.
for(int i = 0; i<(1<<N); ++i)
F[i] = A[i];
for(int i = 0;i < N; ++i) {
for(int mask = 0; mask < (1<<N); ++mask){
if(mask & (1<<i))
F[mask] += F[mask^(1<<i)];
}
}

S(mask,i) 表示第0位到第i位不同的子集

时间复杂度O(N2N)O(N2^N)

tutorial

https://codeforces.com/blog/entry/45223
https://blog.csdn.net/weixin_38686780/article/details/100109753

例题