for(int i = 0; i < (1 << n); i ++)
f[i] = g[i];
for (int i = 0; i < n; i++)
for (int s = 0; s < (1 << n); s++)
if (s >> i & 1)
f[s] += f[s ^ (1 << i)];
```cpp
for (int i = 0; i < n; i++)
for (int s = 0; s < (1 << n); s++)
if (s >> i & 1)
f[s] -= f[s ^ (1 << i)];
```
$g[s]$ 存原来的元素,之后 $f[s]$ 存子集所有元素和
超集求和 $f[s] = \sum_{s \subseteq t} g[t]
for(int i = 0; i < (1 << n); i ++)
f[i] = g[i];
for (int i = 0; i < n; i++)
for (int s = 0; s < (1 << n); s++)
if (s >> i & 1)
f[s ^ (1 << i)] += f[s];
```cpp
for (int i = 0; i < n; i++)
for (int s = 0; s < (1 << n); s++)
if (s >> i & 1)
f[s] -= f[s ^ (1 << i)];
```
复杂度$n2^n$,优于$3^n$枚举算法。
简单讲一下子集求和的原理:假设$T \subseteq S$,$d=|S|-|T|$,
那么传递恰好$d$次后,$T$集合的价值会贡献到$S$,主要问题是,$T$集合可以向$S$至少重复多更新$d$次,所以我们通过把枚举元素的那一层循环移到最外层,保证第$d$次传递后,来更新$S$的且包含$T$的贡献的子集是$\complement_S S_{last}$,也就是除去最后一个元素的$S$集合。
这样就保证不会重复更新了。