树形dp就是在一棵树dp, 状态转移发生在根节点与子节点,求该树在题目背景下的最优解。
hdu1054
Bob enjoys playing computer games, especially strategic games, but sometimes he cannot find the solution fast enough and then he is very sad. Now he has the following problem. He must defend a medieval city, the roads of which form a tree. He has to put the minimum number of soldiers on the nodes so that they can observe all the edges. Can you help him?
Your program should find the minimum number of soldiers that Bob has to put for a given tree.
For example for the tree:
the solution is one soldier ( at the node 1).
题意:给一棵树,树上的每个节点可以放一个哨兵,使该节点相连的边权从0变为1,求至少多少哨兵可以使树上的每一条边权都从0变为1。
题解:设dp[i][true]为i节点放哨兵的最优解,dp[i][false]为i节点不放哨兵的最优解,因为要使所有边都变为1,所以如果i节点不放哨兵,那么他的子节点就都要放才可以把与他相邻的边都变为1;如果i节点放了哨兵,那么他的子节点就可以任意选择放不放哨兵,这时候就变成了子问题,所以记忆化搜索。
#include <cstdio>
#include <cstring>
#define min(a, b) a < b ? a : b
using namespace std;
const int N = 1551;
int Next[N], son[N], edge[N], head[N], dp[N][2], father[N];
int tot, n, m;
bool v[N];
void init() {
memset(Next, -1, sizeof(Next));
memset(head, -1, sizeof(head));
memset(father, 0, sizeof(father));
tot = 0;
}
void add(int x, int y) {
son[++tot] = y, Next[tot] = head[x], head[x] = tot;
}
void dfs(int x) {
dp[x][0] = 0, dp[x][1] = 1;
for (int i = head[x]; i != -1; i = Next[i]) {
int y = son[i];
dfs(y);
dp[x][0] += dp[y][1];
dp[x][1] += min(dp[y][0], dp[y][1]);
}
}
int main() {
int t;
while (~scanf("%d", &t)) {
init();
int a, b, c;
for (int i = 0; i < t; i++) {
scanf("%d:(%d)", &a, &b);
while(b--) {
scanf("%d", &c);
add(a, c);
father[c] = 1;
}
}
int QAQ, i;
for (i = 0; i < t; i++){
if(!father[i]){
dfs(i);
break;
}
}
QAQ = min(dp[i][1], dp[i][0]);
printf("%d\n", QAQ);
}
return 0;
}
最小点覆盖=最大匹配方法↓