天梯赛 小字辈

L2-2 小字辈 (25 分)

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

输入格式:

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

输出格式:

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

输入样例:

9
2 6 5 5 -1 5 6 4 7

输出样例:

4
1 9

 菜鸡的成长史

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int n,d,root,minn=1e6,depth=-1;
 4 vector<int> vec,ve[100005];
 5 vector<int>::iterator it;
 6 void dfs(int root,int rankk) //root记录元素 rankk记录深度
 7 {
 8     if(depth==rankk)
 9         vec.push_back(root);  //同一辈分直接压入
10     if(rankk>depth)  //可以找到更加小的辈分
11     {
12         vec.clear();  //上一辈的要删除;
13         vec.push_back(root);
14         depth=rankk; //更新高度
15     }
16     for(int i=0;i<ve[root].size();i++)
17     {
18         dfs(ve[root][i],rankk+1);
19     }
20     /*for(int i=0;i<n;i++)
21     {
22         if(a[i]==root)
23             dfs(i+1,rankk+1);
24     }*/  //多了这个查找的就超时了
25 }
26 int main()
27 {
28     ios::sync_with_stdio(false);
29     cin>>n;
30     for(int i=1;i<=n;i++)
31     {
32         cin>>d;
33         if(d==-1)
34         {root=i;continue;} //记录下备份最高的
35         ve[d].push_back(i);
36     }
37     dfs(root,1);
38     cout << depth << endl;
39     for(it=vec.begin();it!=vec.end();it++)
40     {
41         if(it!=vec.begin())
42             cout << " ";
43         cout << *it;
44     }
45     cout << endl;
46     return 0;
47 }
View Code
 
 

猜你喜欢

转载自www.cnblogs.com/qq-1585047819/p/10544173.html