Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 140 additions & 0 deletions ShinHeeEul/202502/03 BOJ P5 LCA2 신희을.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
```java
import java.io.*;
import java.util.*;

public class Solution {

static List<Integer>[] lists;
static int[][] parents;
static int[] depths;
static int N;
static Queue<Integer> update = new LinkedList<>();

public static void main(String[] args) throws Exception{
// LCA
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

// 전처리

N = Integer.parseInt(br.readLine());
lists = new ArrayList[N + 1];
parents = new int[N + 1][17];
depths = new int[N + 1];

for(int i = 0; i < N + 1; i++) {
lists[i] = new ArrayList<>();
}

// 내려가면서 tree 만들어
for(int i = 1; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
lists[a].add(b);
lists[b].add(a);
}

//자식 트리 생성
dfs();
// 2^k Parent 배열 만들어
// 2^k+1 번째 부모는 2^k번째 부모의 2^k번째 부모
// parent[i][j + 1] = parent[parent[i][j]][j];

while(!update.isEmpty()) {
int i = update.poll();
for(int j = 0; j < 16; j++) parents[i][j + 1] = parents[parents[i][j]][j];
}


int M = Integer.parseInt(br.readLine());

StringBuilder sb = new StringBuilder();
for(int m = 0; m < M; m++) {
StringTokenizer st = new StringTokenizer(br.readLine());

int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());

// 뎊스 차이만큼 올라가 (뎊스를 맞춰)
int depthA = depths[a];
int depthB = depths[b];

if(depthA > depthB) {
a = calculateDiff(a, depthA - depthB);
} else {
b = calculateDiff(b, depthB - depthA);
}

// 2^k 만큼 올라가면서 부모 찾아
// 일치 하지 않아? 또 올라가
// 일치해? 내려가

for(int i = 16; i >= 0; i--) {
int pa = parents[a][i];
int pb = parents[b][i];

if(pa != pb) {
a = pa;
b = pb;
i++;
}
}
if(a == b) sb.append(a).append("\n");
else sb.append(parents[a][0]).append("\n");
}

System.out.println(sb);


}

public static int calculateDiff(int val, int diff) {
for(int i = 0; diff >= (1 << i); i++) {
int binary = 1 << i;
if((binary | diff) == diff) {
val = parents[val][i];
}
}

return val;
}

public static void dfs() {
Stack<Node> stack = new Stack<>();
boolean[] visited = new boolean[N + 1];

stack.add(new Node(1, 1));
visited[1] = true;
update.add(1);

while(!stack.isEmpty()) {
Node node = stack.pop();

int parent = node.val;
int depth = node.depth;
depths[parent] = depth;
update.add(parent);

for(int a : lists[parent]) {
if(visited[a]) {
parents[parent][0] = a;
continue;
}
visited[a] = true;
stack.push(new Node(a, depth + 1));
}
}
}

public static class Node {
int val;
int depth;

public Node(int val, int depth) {
this.val = val;
this.depth = depth;
}
}

}
```