皇宫看守
https://www.acwing.com/problem/content/1079/
树形dp + 状态机
此题于战略游戏类似, 但是由于要看的是节点而不是边, 所有两个状态不够.
状态表示
- \(f[i][0]:点i被父节点看到\)
- \(f[i][1]:点i被子节点看到\)
- \(f[i][2]:在点i上放守卫\)
- \(属性\ : min\)
状态转移
- \(f[i][2] += \sum min(f[j][1],f[j][2],f[j][0])\)
- \(f[i][0]+=\sum min(f[j][1],f[j][2])\)
- \(f[i][1]比较麻烦,只需要一个子节点j放守卫来看i,这个需要枚举一遍\)
- \(sum=\sum min(f[j][1],f[j][2])\)
- \(f[i][1]=min(f[i][1],sum-min(f[j][1],f[j][2])+f[j][2])\)
代码
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define fi first
#define se second
#define inf 0x3f3f3f3f
const int N = 1510;
int h[N], e[N], ne[N], idx;
int f[N][3], st[N], w[N];
int n;
void add(int a, int b) {
ne[idx] = h[a], e[idx] = b, h[a] = idx++;
}
void dfs(int u) {
f[u][2] = w[u];
int sum = 0;
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
dfs(j);
f[u][0] += min(f[j][1], f[j][2]);
f[u][2] += min(min(f[j][1], f[j][2]), f[j][0]);
sum += min(f[j][1], f[j][2]);
}
f[u][1] = inf;
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
f[u][1] = min(f[u][1], sum - min(f[j][1], f[j][2]) + f[j][2]);
}
}
int main() {
IO;
memset(h, -1, sizeof h);
cin >> n;
for (int i = 1; i <= n; ++i) {
int id, m;
cin >> id >> w[id] >> m;
while (m--) {
int p;
cin >> p;
add(id, p);
st[p] = 1;
}
}
int root;
for (int i = 1; i <= n; ++i)
if (!st[i]) {
root = i;
break;
}
dfs(root);
cout << min(f[root][1], f[root][2]) << '\n';
return 0;
}