[集训笔记7th]dp进阶之树形dp hdu1054

树形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;
}

最小点覆盖=最大匹配方法↓

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值