HDU 1054 Strategic Game

Problem Description

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.

The input file contains several data sets in text format. Each data set represents a tree with the following description:

the number of nodes
the description of each node in the following format
node_identifier:(number_of_roads) node_identifier1 node_identifier2 ... node_identifier
or
node_identifier:(0)

The node identifiers are integer numbers between 0 and n-1, for n nodes (0 < n <= 1500). Every edge appears only once in the input data.

For example for the tree: 

 

the solution is one soldier ( at the node 1).

The output should be printed on the standard output. For each given input data set, print one integer number in a single line that gives the result (the minimum number of soldiers). An example is given in the following table:

Sample Input

4
0:(1) 1
1:(2) 2 3
2:(0)
3:(0)
5
3:(3) 1 4 2
1:(1) 0
2:(0)
0:(0)
4:(0)

Sample Output

1
2

以下采用贪心的方法,即每次选择具有最多未被占用的邻接边的点,直到所有点的邻接边数小于等于0。

但是为什么就是AC不了!!!有没有大神救一下!!

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 

typedef struct Node{
	int length;		//该点周围有多少条未被占用的边 
	int *data;		//该点的临接点
	int parent;		//改点的父节点 
	int son;		//改点的子节点数目 
}Node;

int main(){
	int n;
	int p, q;
	int j;
	while(~scanf("%d", &n)){
		int count = 0;
		getchar();
		Node node[n];	//下标即为点的序号 
		for(int i=0; i<n; i++){
			node[i].parent = 9999;
			node[i].length = 0;
		}
		for(int i=0; i<n; i++){	//输入
			scanf("%d:(%d)", &p, &q);
			node[p].length += q;
			node[p].son = q;
			if(q>0){
				node[p].data = (int *)malloc(q * sizeof(int));
			}
			for(int j=0, d; j<q; j++){
				scanf("%d", &d); node[p].data[j] = d;
				node[d].parent = p;
				node[d].length++;
			}
			getchar();
		}
		//得出结果
		
		while(1){
			int max=0, maxIndex, len;
			for(int i=0; i<n; i++){	//贪心
				if(node[i].length>max){
					max = node[i].length;
					maxIndex = i;
				}
			}
			if(max==0) break;
			if(node[maxIndex].parent!=9999){
				node[node[maxIndex].parent].length--;
			}
			for(int i=0; i<node[maxIndex].son; i++){
				node[node[maxIndex].data[i]].length--;
				node[node[maxIndex].data[i]].parent = 9999;
			}
			node[maxIndex].length = 0;
			count++;
		}
		printf("%d\n", count);
	}
	return 0;
}

心好累,刚试着打题不久,这对萌新是不是不太友好......

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值