L2-026 Junior generation (traversing the tree)

                    L2-026 小字辈 (25分)

This question gives the genealogy of a large family, and asks you to give a list of the youngest generation.

Input format:
Enter the total family population N (a positive integer not exceeding 100 000) in the first line-for simplicity, we number the family members from 1 to N. Then the second line gives N numbers, where the i-th number corresponds to the parent/mother of the i-th member. The ancestor with the highest generation in the family tree corresponds to the parent/mother number -1. The numbers in a row are separated by spaces.

Output format:
first output the smallest generation (the generation of the ancestors is divided into 1, and the following is gradually increasing). Then output the number of the member with the lowest grade in the second line in ascending order. The numbers are separated by a space, and there must be no extra spaces at the beginning and end of the line.

Input sample:

9
2 6 5 5 -1 5 6 4 7

Sample output:

4
1 9

AC code:

#include <bits/stdc++.h>
using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
vector<int>v[100005];//存放结点
int root;//根节点
int L[100005]={
    
    0};//根节点到每个结点的长度 
void DFS(int node,int len){
    
    //结点,当前深度 
	L[node] = len;
	for(int i=0;i<v[node].size();i++){
    
    
		DFS(v[node][i],len+1);
	}
} 
int main(int argc, char *argv[]) {
    
    
	int n,a;
	cin>>n;
	for(int i=1;i<=n;i++){
    
    
		cin>>a;
		if(a==-1){
    
    
			root = i;
		}else{
    
    
			v[a].push_back(i);
		}
	} 
	DFS(root,1);//从根节点开始,长度为1遍历树 
	//找最大深度
	int Max = -1;
	for(int i=1;i<=n;i++){
    
    
		if(L[i]>Max){
    
    
			Max = L[i];
		}
	} 
	cout<<Max<<endl;
	int flat = 1;
	for(int i=1;i<=n;i++){
    
    
		if(L[i]==Max){
    
    
			if(flat){
    
    
				cout<<i;
				flat = 0;
			}else{
    
    
				cout<<" "<<i;
			}
		}
	}
	
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_45880043/article/details/109255564