题目描述
本题给定一个庞大家族的家谱,要请你给出最小一辈的名单。
输入格式
输入在第一行给出家族人口总数 N(不超过 100 000 的正整数) —— 简单起见,我们把家族成员从 1 到 N 编号。随后第二行给出 N 个编号,其中第 i 个编号对应第 i 位成员的父/母。家谱中辈分最高的老祖宗对应的父/母编号为 -1。一行中的数字间以空格分隔。
输出格式
首先输出最小的辈分(老祖宗的辈分为 1,以下逐级递增)。然后在第二行按递增顺序输出辈分最小的成员的编号。编号间以一个空格分隔,行首尾不得有多余空格。
输入样例
9
2 6 5 5 -1 5 6 4 7
输出样例
4
1 9
分析
本题需要存储每个节点peo[]以及其孩子root。 之后进行bfs计算最深的层数,然后输出最深层的所有子结点即可。
C++ 代码
#include<bits/stdc++.h>
using namespace std
;
const int N
= 1e5+10;
vector
<int> root
[N
];
int peo
[N
],depth
[N
];
int n
;
int bfs()
{
int ans
=0;
queue
<int> q
;
q
.push(root
[0][0]);
int t
;
while(q
.size())
{
t
=q
.front();
q
.pop();
for(int j
=0;j
<root
[t
].size();j
++)
{
q
.push(root
[t
][j
]);
depth
[root
[t
][j
]]=depth
[t
]+1;
}
}
return depth
[t
];
}
int main()
{
scanf("%d",&n
);
for(int i
=1;i
<=n
;i
++)
{
scanf("%d",&peo
[i
]);
if(peo
[i
]==-1)
{
peo
[i
]=0;
}
}
for(int i
=1;i
<=n
;i
++)
{
root
[peo
[i
]].push_back(i
);
if(peo
[i
]==0)
depth
[i
]=1;
}
int ger
=bfs();
cout
<<ger
<<endl
;
int f
=0;
for(int i
=1;i
<=n
;i
++)
{
if(depth
[i
]==ger
)
{
if(f
) cout
<<" ";
printf("%d",i
);
f
=1;
}
}
return 0;
}