PAT (Advanced Level) Practice 1094 The Largest Generation

题目链接.

本题考察树的层序遍历,可以用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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值