ZOJ 1134 Strategic Game(树形DP)

题目链接:点击打开链接

题意:一个树形图,在节点上安排士兵,每个士兵能看到与这个节点相连的边,问最少安排多少士兵能看到所有的边

很显然是树形DP,二维数组dp[i][2],dp[i][0]是以当前节点为根的子树,在树根不放士兵的情况下该子树最少安排的士兵;dp[i][1]是以当前节点为根的子树,在树根放士兵的情况下该子树最少安排的士兵

// ZOJ 1134 Strategic Game.cpp 运行/限制:150ms/1000ms
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> tree[1505];
bool book[1505];
int dp[1505][2];
void init() {
	for (int i = 0; i < 1505; i++) {
		tree[i].clear();
	}
	memset(book, false, sizeof(book));
}
int findFather() {
	for (int i = 0; i < 1505; i++) {
		if (book[i] == false) {
			return i;
		}
	}
}
int DP(int fa) {
	dp[fa][1] = 1;
	dp[fa][0] = 0;
	for (int i = 0; i < tree[fa].size(); i++) {
		int v = tree[fa][i];
		DP(v);
		dp[fa][1] += min(dp[v][0], dp[v][1]);
		dp[fa][0] += dp[v][1];
	}
	return min(dp[fa][0], dp[fa][1]);
}
int main(){
	int n, fa;
	int u, v, cnt;
	while (scanf("%d", &n) != EOF) {
		init();
		for (int i = 0; i < n; i++) {
			scanf("%d", &u);
			getchar();getchar();
			scanf("%d", &cnt);
			getchar();
			for (int j = 0; j < cnt; j++) {
				scanf("%d", &v);
				tree[u].push_back(v);
				book[v] = true;
			}
		}
		fa = findFather();
		printf("%d\n",DP(fa));
	}
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值