团体天梯 L2-026 小字辈 (25 分)

版权声明:有疑问请在评论区回复,邮箱:[email protected] https://blog.csdn.net/qq_40946921/article/details/86626955

L2-026 小字辈 (25 分)

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

输入格式:

输入在第一行给出家族人口总数 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<vector>
#include<set>
#include<map>
using namespace std;
typedef struct Person {
	vector<int> children;
};
pair<int, set<int>> result;
map<int, Person> people;
void search(int i,int k) {
	if (k >= result.first) {
		if (k > result.first) {
			result.second.clear();
			result.first = k;
		}
		result.second.insert(i);
	}
	for (auto &it : people[i].children) 
		search(it, k + 1);
}
int main() {
	int n, id;
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> id;
		people[id].children.push_back(i);
	}
	search(-1, 0);
	cout << result.first << endl;
	for (auto it = result.second.begin(); it != result.second.end(); it++) {
		if (it != result.second.begin()) cout << " ";
		cout << *it;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40946921/article/details/86626955