PAT-A1004. Counting Leaves (30)

Posted 王景迁

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT-A1004. Counting Leaves (30)相关的知识,希望对你有一定的参考价值。

  根据家谱树从根结点开始输出每一层的叶子结点数量。使用BFS来解决。因为不会重复访问结点,所以不需要vis数组来标记是否访问过该结点。

 

 1 //#include "stdafx.h"
 2 #include <iostream>
 3 #include <vector>
 4 #include <queue>
 5 
 6 using namespace std;
 7 
 8 vector<int> node[101]; // Storing children\'s dynamic arrays
 9 queue<int> que; // que for bfs
10 bool first = true; // first output flag
11 
12 void bfs() { // traverse by layer
13     int queSize = que.size(), cur, nodeSize, count = 0, i;
14     while (queSize--) { // traverse all nodes at the current level
15         cur = que.front();
16         que.pop();
17 
18         nodeSize = node[cur].size();
19         if (nodeSize == 0) { // if it is a leaf node
20             count++;
21         } else {
22             for (i = 0; i < nodeSize; i++) { // if not, add child node
23                 que.push(node[cur][i]);
24             }
25         }
26     }
27 
28     // output
29     if (first) {
30         first = false;
31     } else {
32         printf(" ");
33     }
34     printf("%d", count);
35 
36     if (que.size() > 0) { // if que has elements, traverse
37         bfs();
38     }
39 }
40 
41 int main() {
42     int n, m;
43     scanf("%d%d", &n, &m);
44 
45     int i, id, k, child, j;
46     for (i = 0; i < m; i++) {
47         scanf("%d%d", &id, &k);
48 
49         for (j = 1; j <= k; j++) {
50             scanf("%d", &child);
51             node[id].push_back(child);
52         }
53     }
54 
55     que.push(1); // add root node
56     bfs();
57     printf("\\n");
58 
59     system("pause");
60     return 0;
61 }
View Code

 

以上是关于PAT-A1004. Counting Leaves (30)的主要内容,如果未能解决你的问题,请参考以下文章

1004 Counting Leaves (30)(30 分)

PAT甲1004 Counting Leavesdfs

PAT1004:Counting Leaves

1004 Counting Leaves (30 分)

1004. Counting Leaves (30)

1004. Counting Leaves (30)