小字辈 (bfs好题)

小字辈 (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 <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <vector>
 5 #include <queue>
 6 #include <algorithm>
 7 using namespace std;
 8 const int maxn=1e5+10;
 9 vector<int> v[maxn];
10 vector<int> f[maxn];
11 int n,x;
12 int high;
13 int parent;
14 void bfs()
15 {
16     queue<int>q;
17     q.push(parent);
18     high=0;
19     f[high].push_back(parent);
20 
21     while(!q.empty())
22     {
23 
24         int sum=q.size();
25         high++;
26         for(int i=0;i<sum;i++)
27         {
28             int head=q.front();
29             q.pop();
30             for(int j=0;j<v[head].size();j++)
31             {
32                 f[high].push_back(v[head][j]);
33                 q.push(v[head][j]);
34             }
35 
36         }
37     }
38 }
39 int main()
40 {
41     cin>>n;
42     for(int i=1;i<=n;i++)
43     {
44         scanf("%d",&x);
45         if(x>0)
46             v[x].push_back(i);
47         else
48             parent=i;
49     }
50     bfs();
51     cout<<high<<endl;
52     for(int i=0;i<f[high-1].size();i++)
53     {
54         if(i!=0)
55             printf(" ");
56 
57             printf("%d",f[high-1][i]);
58     }
59     cout<<endl;
60     return 0;
61 }
 

猜你喜欢

转载自www.cnblogs.com/1013star/p/9750803.html
今日推荐