PATA1004题解

 1 #include<iostream>
 2 #include<cstring>
 3 #include<stdio.h>
 4 #include<vector>
 5 #include<queue>
 6 using namespace std;
 7 typedef pair<int,int> P;
 8 const int MAXN = 105;
 9 int level = 0;
10 vector<int>point[MAXN];
11 int ans[MAXN];
12 void print() {
13     queue<P> que;
14     que.push(P(1,0));
15     while(!que.empty()) {
16         P p = que.front(); que.pop();
17         int len = point[p.first].size();
18         if( len == 0) {
19             ans[p.second] ++;
20         }else {
21             for(int i = 0; i < len; i++) {
22                 que.push(P( point[p.first][i] , p.second+1));
23             }
24             level = max(level,p.second+1);
25         }
26     }
27 }
28 int main () {
29     int points_num, non_leaf, cur_index, len, cur_child;
30     cin >> points_num ;
31     if(points_num == 0) return 0;
32     cin >> non_leaf;
33     for(int i = 1;i <= non_leaf; i++) {
34         cin >> cur_index >> len;
35         for(int j = 1; j <= len;j++) {
36             cin >> cur_child;
37             point[cur_index].push_back(cur_child); ///之前这里写成了i,但是PAT竟然只有一个测试样例没过。。。。
38         }
39     }
40     print();
41     for(int i = 0; i <= level; i++) {
42         
43         printf("%d",ans[i]);
44         if(level != i) printf(" ");
45     }
46 }

套用的是算法笔记一道类似的题目的代码,通过广度优先搜索 解决 层序遍历的问题。

猜你喜欢

转载自www.cnblogs.com/dcklm/p/10339550.html
今日推荐