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;
}
心好累,刚试着打题不久,这对萌新是不是不太友好......