PAT A1094 The Largest Generation
Sample Input:
23 13
21 1 23
01 4 03 02 04 05
03 3 06 07 08
06 2 12 13
13 1 21
08 2 15 16
02 2 09 10
11 2 19 20
17 1 22
05 1 11
07 1 14
09 1 17
10 1 18
Sample Output:
9 4
word | meaning |
---|---|
hierarchy | n. 层级;等级制度 |
pedigree | n. 血统;家谱 |
-
题意:
找结点最多的层,求该层的结点数,和所在层数 -
思路 1:
- BFS,用
vector<int> child[maxn]
存储树,用一个layer[]记录当前结点的层数,用一个dep[i]数组记录 第i层的结点数 - 每次遍历child时,使孩子的层数为父亲的+1:
layer[child] = layer[now]+1;
,对应层数的结点个数++; - 最后dep[i]即第i层的结点数,遍历输出即可
- code 1:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n, m; //n: 总数 m:有孩子的(非叶节点); 编号1-n ;root = 1
const int maxn = 110;
vector<int> child[maxn];
int dep[maxn], layer[maxn], ly = 0;
void BFS(int root){
queue<int> q;
q.push(root);
layer[root] = 1;
dep[layer[root]] = 1;
while(!q.empty()){
int now = q.front();
q.