状压dp
图上怎么跑dp?我们跑三进制状压dp,0表示选了,1表示既没选也没覆盖,2表示没选但是被覆盖了。
状态是dp[dep][S]表示当前走到了深度为dep的节点,状态为S,按照dfs序转移
每次转移就是计算这个点选了没选,然后像树形dp一样更新节点
返祖边也要处理
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include<bits/stdc++.h> using namespace std; const int N = 5e4 + 5; int n, m, ans; vector<int> G[N]; int dp[11][N], c[N], vis[N], bin[11], st[N], d[N]; inline int rd() { int x = 0, f = 1; char c = getchar(); 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 bit(int S, int t) { return S / bin[t] % 3; } void dfs(int u, int dep) { vis[u] = 1; d[u] = dep; if(!dep) { dp[0][0] = c[u]; dp[0][1] = 0; dp[0][2] = 1e9; } else { int top = 0; for(int i = 0; i < G[u].size(); ++i) { int v = G[u][i]; if(d[v] < d[u] && vis[v]) st[++top] = d[v]; } for(int i = 0; i < bin[dep + 1]; ++i) dp[dep][i] = 1e9; for(int i = 0; i < bin[dep]; ++i) { int U = 1, V = i; for(int j = 1; j <= top; ++j) if(bit(i, st[j]) == 0) U = 2; else if(bit(i, st[j]) == 1) V += bin[st[j]]; dp[dep][i + U * bin[dep]] = min(dp[dep][i + U * bin[dep]], dp[dep - 1][i]); dp[dep][V] = min(dp[dep][V], dp[dep - 1][i] + c[u]); } } for(int i = 0; i < G[u].size(); ++i) { int v = G[u][i]; if(vis[v]) continue; dfs(v, dep + 1); for(int j = 0; j < bin[dep + 1]; ++j) dp[dep][j] = min(dp[dep + 1][j], dp[dep + 1][j + 2 * bin[dep + 1]]); } } int main() { n = rd(); m = rd(); bin[0] = 1; for(int i = 1; i <= 10; ++i) bin[i] = bin[i - 1] * 3; for(int i = 1; i <= n; ++i) c[i] = rd(); for(int i = 1; i <= m; ++i) { int u = rd(), v = rd(); G[u].push_back(v); G[v].push_back(u); } for(int i = 1; i <= n; ++i) if(!vis[i]) { dfs(i, 0); ans += min(dp[0][0], dp[0][2]); } printf("%d\n", ans); return 0; }