PAT 1004. Counting Leaves (30)

链接: http://www.patest.cn/contests/pat-a-practise/1004

复习一下C

  1 #include<stdio.h>

  2 #include<string.h>

  3 #include<ctype.h>

  4 #include<stdlib.h>

  5 

  6 #define MAX_NODE 110

  7 #define MAX_QUEUE_SIZE 110

  8 

  9 typedef struct {

 10     int *child;

 11     int child_size;

 12     int deep;

 13 } tree_node;

 14 tree_node nodes[MAX_NODE];

 15 

 16 int result_cnt;

 17 int result[MAX_NODE];

 18 

 19 int rear = -1;

 20 int front = -1;

 21 int queue[MAX_QUEUE_SIZE];

 22 

 23 void addq(int *rear, int item)

 24 {

 25     if (*rear == MAX_QUEUE_SIZE - 1) { //full queue

 26         return;

 27     }

 28     queue[++*rear] = item;

 29 }

 30 

 31 int deleteq(int *front, const int rear)

 32 {

 33     if (*front == rear) { //empty queue

 34         return;

 35     }

 36     return queue[++*front];

 37 }

 38 

 39 int is_empty()

 40 {

 41     return front == rear;

 42 }

 43 

 44 void initq()

 45 {

 46     memset(queue, 0, sizeof(queue));

 47     rear = front = -1;

 48 }

 49 

 50 void level_order()

 51 {

 52     int i;

 53     initq();

 54     addq(&rear, 1);

 55     nodes[1].deep = 0;

 56     while(!is_empty()) {

 57         int u = deleteq(&front, rear);

 58         int deep = nodes[u].deep;

 59         if (0 == nodes[u].child_size) {

 60             ++result[deep];

 61             result_cnt = deep;

 62             continue;

 63         }

 64         for (i = 0; i < nodes[u].child_size; ++i) {

 65             addq(&rear, nodes[u].child[i]);

 66             nodes[nodes[u].child[i]].deep = deep + 1;

 67         }

 68     }

 69 }

 70 

 71 void init()

 72 {

 73     int i = 0;

 74     memset(result, 0, sizeof(result));

 75     result_cnt = 0;

 76     for (i = 1; i < MAX_NODE; ++i) {

 77         nodes[i].child = NULL;

 78         nodes[i].child_size = 0;

 79         nodes[i].deep = 0;

 80     }

 81 }

 82 int main(int argc, char **argv)

 83 {

 84     init();

 85     int n, m, i, j;

 86     int id, k, child_id;

 87     scanf("%d%d", &n, &m);

 88     for (i = 0; i < m; ++i) {

 89         scanf("%d%d", &id, &k);

 90         nodes[id].child_size = k;

 91         nodes[id].child = (int *)malloc(sizeof(int)*k);

 92         for (j = 0; j < k; ++j) {

 93             scanf("%d", &child_id);

 94             nodes[id].child[j] = child_id;

 95         }

 96     }

 97     level_order();

 98     printf("%d", result[0]);

 99     for (i = 1; i <= result_cnt; ++i) {

100         printf(" %d", result[i]);

101     }

102     puts("");

103     return 0;

104 }

 

你可能感兴趣的:(count)