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
", MIN(soldiers[root][0], soldiers[root][1])); } return 0; }

좋은 웹페이지 즐겨찾기