[PTA] L2-026 Junior (25 points) [DFS]

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:
output the smallest generation first (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

Code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=100020;
int n,p,deep=1,d[maxn]={
    
    0},root; //deep:最大层数  d:节点的深度   root:祖宗 
vector<int> g[maxn],ans[maxn];   // g:父母->孩子   ans:各深度的所有节点 

void dfs(int u) //遍历深度 
{
    
    
	for(int i=0;i<g[u].size();i++)
	{
    
    
		int v=g[u][i];
		d[v]=d[u]+1;   
		deep=max(deep,d[v]);  //更新最大层数 
		ans[d[v]].push_back(v); //v为深度d[v]的一个节点 
		dfs(v);
	}
}

int main()
{
    
    	    
	cin>>n;
	for(int i=1;i<=n;i++)
	{
    
    
		cin>>p;
		if(p==-1) root=i; //根 
		else g[p].push_back(i);  
	}
	
	d[root]=1; 
	ans[1].push_back(root);
	dfs(root);
	
	cout<<deep<<endl;
	for(int i=0;i<ans[deep].size();i++)  //没排序也可以过 
	{
    
    
		cout<<ans[deep][i];
		if(i<ans[deep].size()-1) cout<<" ";
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45260385/article/details/110092553