HDU 1054 Strategic Game (树形DP)

#include <stdio.h>
#define MAX_NODES 1500
#define MIN(x, y) ( (x) < (y) ? (x) : (y) )

int numOfNodes;
int root;
int numOfRoads;
typedef struct Road{
	int to;
	int next;
}Road;
Road RoadArray[MAX_NODES * MAX_NODES + 1];
int RoadNum;
int head[MAX_NODES + 1];
int visited[MAX_NODES + 1];
int soldiers[MAX_NODES + 1][2];

void addRoad(int from, int to){
	RoadNum++;
	RoadArray[RoadNum].to = to;
	RoadArray[RoadNum].next = head[from];
	head[from] = RoadNum;
}

void putSoldierOrNot(int from){
	soldiers[from][0] = 0;
	soldiers[from][1] = 1;
	int i, to;
	for (i = head[from]; i != 0; i = RoadArray[i].next){
		to = RoadArray[i].to;
		if (visited[to] == 0){
			visited[to] = 1;
			putSoldierOrNot(to);
			//如果父节点不放,子节点必须放
			soldiers[from][0] += soldiers[to][1];
			//如果父节点放,子节点可放可不放
			soldiers[from][1] += MIN(soldiers[to][0], soldiers[to][1]);
		}
	}
}

int main(){
	freopen("input.txt", "r", stdin);
	while (scanf("%d", &numOfNodes) != EOF){
		RoadNum = 0;
		root = -1;
		int i;
		for (i = 0; i < numOfNodes; i++){
			visited[i] = 0;
			head[i] = 0;
		}

		int j, from, to;
		for (i = 0; i < numOfNodes; i++){
			scanf("%d:(%d)", &from, &numOfRoads);
			if (root = -1)
				root = from;
			for (j = 0; j < numOfRoads; j++){
				scanf("%d", &to);
				addRoad(from, to);
				addRoad(to, from);
			}
		}

		visited[root] = 1;
		putSoldierOrNot(root);

		printf("%d\n", MIN(soldiers[root][0], soldiers[root][1]));

	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值