PTA L2-026

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
21
3
48
53,4,6
62,7
79
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;
}
/*

*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值