题目链接.
本题考察树的层序遍历,可以用dfs或者bfs进行求解,用hashtable记录树的每一层的结点总数
这里只介绍了bfs的写法
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int maxn=110;
int hashtable[maxn]={0};
struct node{
int layer;
vector<int> child;
}peo[maxn];
void bfs(int root){
peo[root].layer=1;
hashtable[root]+=1;
queue<int> q;
q.push(root);
while(!q.empty()){
int front=q.front();
q.pop();
for(int i=0; i<peo[front].child.size(); i++){
int child=peo[front].child[i];
peo[child].layer=peo[front].layer+1;
hashtable[peo[child].layer]+=1; //利用hashtable计算和储存树的每一层的结点总数
q.push(child);
}
}
}
int main()
{
int n, m, p, k, c;
scanf("%d%d", &n, &m);
while(m--){
scanf("%d%d", &p, &k);
while(k--){
scanf("%d", &c);
peo[p].child.push_back(c);
}
}
bfs(1);
int maxvalue=-1, maxlayer=-1;
for(int i=1; i<=n; i++){
if(hashtable[i]>maxvalue){
maxvalue=hashtable[i];
maxlayer=i;
}
}
printf("%d %d\n", maxvalue, maxlayer);
return 0;
}