Newguy


私信TA

用户名:772007765

访问量:82108

签 名:

已秃人士

等  级
排  名 28
经  验 14598
参赛次数 3
文章发表 92
年  龄 0
在职情况 在职
学  校
专  业

  自我简介:

描述

ACMCLUB王国有n+1座城市,标号分别是0到n,并且所有城市构成树状结构。0是国王所在的城市,相当于树状结构中的根。其他城市的成熟度定义为从0到该城市所包含的城市数(不包括0和该城市自己)。我们把最大的那个城市的成熟度作为整个王国的成熟度,现在我们想知道王国成熟度是多少。

输入

输入第一行为整数n(n<=10000),接下来有n行,每行输入一个数字,第i行表示节点i的父节点。数据保证构成一棵树。

输出

对于每组输入,输出一行,表示王国的成熟度。

样例输入1

5
3
3
0
2
0

样例输出1

2

import java.util.*;  
  
public class Main  {  
	
	static class City {
		int f;  //父节点
		int depth;
		boolean flag = false;  //是否遍历过
		
		City(int a, int b){
			f = a;
			depth = b;
		}
	}
	
	static City[] city;
	
	public static int locDepth(int i) {
		if (city[i].f == 0)
			city[i].depth = 0;
		else
			city[i].depth = locDepth(city[i].f) + 1;
		city[i].flag = true;
		return city[i].depth;
	}
	
    public static void main(String args[]){  
        Scanner input = new Scanner(System.in);  
        while (input.hasNext()) {
        	int n = input.nextInt();
        	city = new City[n+1];
        	for (int i = 1; i <= n; i++)
        		city[i] = new City(input.nextInt(), 0);
        	for (int i = 1; i <= n; i++)
        		if (!city[i].flag)
        			locDepth(i);
        	int max = 0;
        	for (int i = 1; i <= n; i++)
        		max = Math.max(max, city[i].depth);
        	System.out.println(max);
        }
    }  
}


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区