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
思路:
- 建立邻接表
家庭成员 | 子节点 |
---|---|
1 | |
2 | 1 |
3 | |
4 | 8 |
5 | 3,4,6 |
6 | 2,7 |
7 | 9 |
8 | |
9 |
-
找出家谱中辈分最高的老祖宗,并记录其下标
样例老祖中的下标为5
-
深搜(dfs),找到没有子节点并且辈分最小的节点
c++代码
#include <map>
#include <set>
#include <regex>
#include <stack>
#include <queue>
#include <math.h>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int dir[4][2] = { {1,0} ,{-1,0},{0,1},{0,-1} };
void dfs(vector<vector<int>>& parent, vector<int>& ans, int ancestorPos, int& minCnt, int nowCnt) {
if (minCnt < nowCnt && parent[ancestorPos].size() == 0) {
minCnt = nowCnt;
ans.clear();
}
if (minCnt == nowCnt) {
ans.push_back(ancestorPos);
}
for (int t : parent[ancestorPos]) {
dfs(parent, ans, t, minCnt, nowCnt + 1);
}
}
int main()
{
int N;
cin >> N;
int ancestorPos = 0;
vector<vector<int>> parent(N + 1);
for (int i = 1; i <= N; i++) {
int t;
cin >> t;
if (t == -1) {
ancestorPos = i;
continue;
}
parent[t].push_back(i);
}
int minCnt = 0;
int nowCnt = 1;
vector<int> ans;
dfs(parent, ans, ancestorPos, minCnt, nowCnt);
cout << minCnt << endl;
sort(ans.begin(), ans.end());
for (int i = 0; i < ans.size(); i++) {
if (i != 0) {
cout << " ";
}
cout << ans[i];
}
return 0;
}
/*
*/