版本比较
奶龙学习笔记之动态规划 Ⅱ
正文
增加 76 行删除 0 行
242 行未改动全部展开243244245246242 行未改动全部展开[题解链接](https://www.luogu.com.cn/article/5htl7sa0)**注:** 题解里有个人想法(也许算 trick)。242 行未改动全部展开243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322242 行未改动全部展开[题解链接](https://www.luogu.com.cn/article/5htl7sa0)**注:** 题解里有个人想法(也许算 trick)。---## P3349 [ZJOI2016] 小星星[题目链接](https://www.luogu.com.cn/problem/P3349)容斥优化 dp首先这个问题等价于把树上的点重新编号,要求重新编号的点在图上相邻。不难设计出暴力 dp:设 $dp_{u,s,x}$ 表示在以 $u$ 为根的子树中选的点集为 $s$,$u$ 的点是 $x$ 的方案数($s$ 是状压后的点集)。直接转移大概是个类似背包的东西,要枚举子集,时间复杂度 $O(3^n n^3)$。考虑优化。我们发现枚举子集这个东西很烦人,那么为什么要枚举子集呢?因为每个点重新编号后必须**恰好出现一次**。如果每个点都可以出现任意次,那么我们便可直接 $O(n^3)$ 求出。于是考虑枚举点集,然后直接容斥。点集 $s$ 的容斥系数为 $(-1)^{n-\operatorname{popcnt}(s)}$。::::success[代码]```cpp#include <bits/stdc++.h>#define ll long long#define eb emplace_backusing namespace std;const int maxn = 20, maxm = 205;int n, m;ll dp[maxn][maxn];vector <int> e[maxn];bool g[maxn][maxn];void dfs(int x, int fa, int s) {for(int i = 1; i <= n; i++) dp[x][i] = (s & (1 << (i - 1))) ? 1 : 0;for(int y : e[x]) {if(y == fa) continue;dfs(y, x, s);for(int i = 1; i <= n; i++) {if(!(s & (1 << (i - 1)))) continue;ll val = 0;for(int j = 1; j <= n; j++) {if(!(s & (1 << (j - 1)))) continue;if(g[i][j]) val += dp[y][j];}dp[x][i] *= val;}}}int main() {scanf("%d%d", &n, &m);int u, v;for(int i = 1; i <= m; i++) {scanf("%d%d", &u, &v);g[u][v] = g[v][u] = 1;}for(int i = 1; i < n; i++) {scanf("%d%d", &u, &v);e[u].eb(v), e[v].eb(u);}ll ans = 0;for(int i = 1; i < (1 << n); i++) {dfs(1, 0, i);ll sum = 0; int pcnt = 0;for(int j = 1; j <= n; j++) {if(!(i & (1 << (j - 1)))) continue;pcnt++;sum += dp[1][j];}if((n - pcnt) & 1) ans -= sum;else ans += sum;}printf("%lld\n", ans);return 0;}```::::