#37170: java的解答(單筆測資)


zhoudaniel02@gmail.com (周孝倫)

學校 : 銘傳大學
編號 : 235507
來源 : [163.20.87.251]
最後登入時間 :
2024-05-07 15:54:08
b967. 4. 血緣關係 -- 2016年3月apcs | From: [114.136.209.94] | 發表日期 : 2023-08-23 17:39

package apcsPrat;

import java.util.*;

class node697 {

boolean ishead=true;

int data;

int age;

node697 father;

List<node697>child=new ArrayList<>();

List<node697>grand=new ArrayList<>();

public node697(int data) {

this.data=data;

}

public void addchild(node697 child) {

this.child.add(child);

child.father=this;

}

}

public class b967 {

public static node697 head;

public static List<node697>fam=new ArrayList<>();

public static int distance(node697 a,node697 b) {

if(a==b)

return 0;

if(a==head)

return b.age;

if(b==head)

return a.age;

int max=-1;

for(node697 af:a.grand)

for(node697 bf:b.grand)

if(af==bf&max<af.age) {

max=af.age;

}

return a.age-max+b.age-max;

}

public static void main(String [] args) {

Scanner sc=new Scanner(System.in);

head=null;

fam.clear();

int total=sc.nextInt();

for(int i=0;i<total;i++) {

fam.add(new node697(i));

}

sc.nextLine();

for(int i=0;i<total-1;i++) {

String [] s=sc.nextLine().split(" ");

int a=Integer.parseInt(s[0]);

int b=Integer.parseInt(s[1]);

fam.get(a).addchild(fam.get(b));

}

for(node697 e:fam) {

for(node697 f:e.child)

f.ishead=false;

}

for(node697 e:fam) {

if(e.ishead==true) {

head=e;

}

}

for(node697 e:fam) {

node697 dat=e;

e.grand.add(e);

while(dat!=head) {

dat=dat.father;

e.grand.add(dat);

}

e.age=e.grand.size()-1;

}

int far=0;

for(node697 a:fam)

for(node697 b:fam)

if(far<distance(a,b))

far=distance(a,b);

System.out.println(far);

sc.close();

}

}

 
ZeroJudge Forum