-
Notifications
You must be signed in to change notification settings - Fork 0
/
BJ11438.java
113 lines (102 loc) Β· 3.06 KB
/
BJ11438.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class BJ11438 {
static ArrayList<Integer>[] tree;
static int[][] parents;
static int[] depths;
static boolean[] visited;
static int kmax;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringTokenizer st;
tree = new ArrayList[N+1];
for(int i = 0; i<=N; i++){
tree[i] = new ArrayList<>();
}
for(int i = 0; i<N-1; i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
tree[a].add(b);
tree[b].add(a);
}
int temp = 1;
kmax = 0;
while(temp<=N){
temp <<= 1;
kmax++;
}
parents = new int[kmax+1][N+1];
depths = new int[N+1];
visited = new boolean[N+1];
BFS(1);
for(int i = 1; i<=kmax; i++){
for(int j = 1; j<=N; j++){
parents[i][j] = parents[i - 1][parents[i-1][j]];
}
}
int M = Integer.parseInt(br.readLine());
for(int i = 0; i<M; i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
System.out.println(findParents(a,b));
}
}
private static void BFS(int start){
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
visited[start] = true;
int depth = 1;
int count = 0;
int now_size = 1;
while(!queue.isEmpty()){
int now = queue.poll();
for(int next : tree[now]){
if(!visited[next]){
visited[next] = true;
queue.add(next);
parents[0][next] = now;
depths[next] = depth;
}
}
count++;
if(count == now_size){
count = 0;
now_size = queue.size();
depth++;
}
}
}
private static int findParents(int a, int b){
if(depths[a]>depths[b]){
int temp = a;
a = b;
b = temp;
}
for(int k = kmax; k>=0; k--){
if(Math.pow(2, k) <= depths[b] - depths[a]){
if(depths[a] <= depths[parents[k][b]]){
b = parents[k][b];
}
}
}
for(int k = kmax; k>=0; k--){
if(parents[k][a] != parents[k][b]){
a = parents[k][a];
b = parents[k][b];
}
}
int LCA = a;
if(a!=b){
LCA = parents[0][LCA];
}
return LCA;
}
}