小字辈(递归找根节点)

7-3 小字辈
分数 25
作者 陈越
单位 浙江大学

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

输入格式:

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

输出格式:

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

输入样例:

9
2 6 5 5 -1 5 6 4 7

输出样例:

4
1 9
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
 
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<cmath>
#include<stdlib.h> 
using namespace std;

const int N = 100010;
int n,m;
int p[N]; int countp[N];

int count(int i) {
    if (countp[i] == 0) {//等于0就说明没有更新过,要进行求解
        int cont;
        if (p[i] != -1) {
            cont = count(p[i]) + 1;//递归求出相应层数
        }
        else {
            cont = 1;
        }
        countp[i] = cont;//记录对应层数,再用是直接用就行
        return cont;
    }
    else {
        return countp[i];
    }
}

int main()
{
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    cin >> n; int a;
    for (int i = 1; i <= n; i++) {
        cin >> a;
        p[i] = a;
    }
    int maxx = 0;
    for (int i = 1; i <= n; i++) {
        maxx = max(count(i), maxx);
    }
    cout << maxx << endl;
    int f = 0;
    for (int i = 1; i <= n; i++) {
        if (countp[i] == maxx) {
            if (f == 1) cout << " ";
            cout << i;
            f = 1;
        }
    }
    cout << endl;
    return 0;
}

 

 
 
posted @ 2024-01-28 20:08  敲代码的6  阅读(88)  评论(0)    收藏  举报