PTA小字辈(BFS)

本题给定一个庞大家族的家谱,要请你给出最小一辈的名单。

输入格式:

输入在第一行给出家族人口总数 N(不超过 100 000 的正整数) —— 简单起见,我们把家族成员从 1 到 N 编号。随后第二行给出 N 个编号,其中第 i 个编号对应第 i 位成员的父/母。家谱中辈分最高的老祖宗对应的父/母编号为 -1。一行中的数字间以空格分隔。

输出格式:

首先输出最小的辈分(老祖宗的辈分为 1,以下逐级递增)。然后在第二行按递增顺序输出辈分最小的成员的编号。编号间以一个空格分隔,行首尾不得有多余空格。

输入样例:

9
2 6 5 5 -1 5 6 4 7

输出样例:

4
1 9

其实主要是存储的数据结构的设计。

#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<list>
#include<set>
#include<cmath>
using namespace std;
typedef long long ll;
struct node{
	int father;
	vector<int> child;
}family[100005];
queue<int> qu;
vector<int> level;
int maxh = 1;
void bfs(int root){
	qu.push(root);
	level[root] = 1;
	while(qu.size()){
		int index = qu.front();
		qu.pop();
		vector<int> tmp = family[index].child;
		for(int i=0;i<tmp.size();i++){
			level[tmp[i]] = level[index]+1;
			maxh = max(level[tmp[i]],maxh);
			qu.push(family[index].child[i]); 
		}
	}
}
int main(){
	int n,x,root;
	cin >> n;
	level.resize(n+1);
	for(int i=1;i<=n;i++){
		cin >> family[i].father;
		if(family[i].father==-1) root = i;
		else {
			family[family[i].father].child.push_back(i);
		}
	}
	bfs(root);
	cout << maxh << endl;
	int first = 1;
	for(int i=1;i<=n;i++){
		if(level[i]==maxh){
			if(first) {
				cout << i ; first = 0;
			}
			else cout << " " << i ; 
		}
		 
	}
	return 0;
}

发布了63 篇原创文章 · 获赞 34 · 访问量 6550

猜你喜欢

转载自blog.csdn.net/SinclairWang/article/details/104045618