没有通过,改天多找几个用例测试一下
package info.frady.poj;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class P1330 {
static int[] pid;//存放每个节点的父亲节点
static int[] lev;//存放每个节点的层级
static List<Integer>[] list;//存放节点的关系
public static void main(String[] args) throws Exception{
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
int T=Integer.parseInt(reader.readLine());
//String str=reader.readLine();
//String str[]=reader.readLine().split(" ");
for (int i = 0; i <T ; i++) {
int N=Integer.parseInt(reader.readLine());
list=new ArrayList[N+1];
pid=new int[N+1];
lev=new int[N+1];
for (int j = 0; j < N+1; j++) {
pid[j]=j;
list[j]=new ArrayList<Integer>();
}
for (int j = 1; j <N ; j++) {// N-1 行关联关系
String str[]=reader.readLine().split(" ");//前面的是父节点,后面的是子节点
int m=Integer.parseInt(str[0]);//父节点
int n=Integer.parseInt(str[1]);//子节点
pid[n]=m;
list[m].add(n);
}
int p=0;
for (int j = 1; j < N+1; j++) {//找到跟节点
if(pid[j]==j){
p=j;
break;
}
}
BFS(p);//划分下层级
String str[]=reader.readLine().split(" ");
int m=Integer.parseInt(str[0]);
int n=Integer.parseInt(str[1]);
System.out.println(findCommonPid(m,n));
}
reader.close();
}
public static int findCommonPid(int m,int n){
int ml=lev[m];
int nl=lev[n];
if(ml== nl){
while(ml!=1){
int M=pid[m];
int N=pid[n];
if(M==N){
return M;
}
m=M;
n=N;
ml--;
}
}else if(ml>nl){//m比n层级深,m可能是n的子节点
int diff=ml-nl;
while(diff!=0){
int M=pid[m];
m=M;
diff--;
}
if(m==n){
return m;
}
}else if(ml<nl){//m比n层级浅,n可能是m的子节点
int diff=nl-ml;
while(diff!=0){
int N=pid[n];
n=N;
diff--;
}
if(m==n){
return m;
}
}
return 0;
}
public static void BFS(int start){
LinkedList<Integer> li=new LinkedList<Integer>();
int l=0;
li.add(start);
while ( ! li.isEmpty()){
l++;
int size=li.size();
for (int i = 0; i <size ; i++) {//这一波走完
int a=li.pop();
lev[a]=l;
for (int m:list[a]) {
li.add(m);
}
}
}
}
public static int find(int a){
if(pid[a] == a){
return pid[a];
}else{
return find(pid[a]);
}
}
}
自己造的用例
1
16
1 14
8 5
10 16
5 9
4 6
8 4
4 10
1 13
6 15
10 11
6 7
10 2
16 3
8 1
16 12
16 6
==4
1
16
1 14
8 5
10 16
5 9
4 6
8 4
4 10
1 13
6 15
10 11
6 7
10 2
16 3
8 1
16 12
15 10
==4
1
16
1 14
8 5
10 16
5 9
4 6
8 4
4 10
1 13
6 15
10 11
6 7
10 2
16 3
8 1
16 12
15 14
==8
1
16
1 14
8 5
10 16
5 9
4 6
8 4
4 10
1 13
6 15
10 11
6 7
10 2
16 3
8 1
16 12
15 13
==8
1
16
1 14
8 5
10 16
5 9
4 6
8 4
4 10
1 13
6 15
10 11
6 7
10 2
16 3
8 1
16 12
1 14