본문 바로가기

PS/Problems

[Java] 백준 11438번 LCA 2 - LCA (최소 공통 조상)

https://www.acmicpc.net/problem/11438

 

11438번: LCA 2

첫째 줄에 노드의 개수 N이 주어지고, 다음 N-1개 줄에는 트리 상에서 연결된 두 정점이 주어진다. 그 다음 줄에는 가장 가까운 공통 조상을 알고싶은 쌍의 개수 M이 주어지고, 다음 M개 줄에는 정

www.acmicpc.net

https://pangtrue.tistory.com/262

 

[백준 11438 : JAVA] LCA 2 / 최소 공통 조상

문제 풀이 LCA(Lowest Common Acestor_최소 공통 조상) 알고리즘을 사용하는 기본 유형의 문제다. 해당 문제에서 주의깊게 봐둬야할 건 각 노드의 2^i 번 째 조상노드를 테이블에 저장하기 위해 DP를 사용

pangtrue.tistory.com

import java.util.*;
import java.io.*;

public class p5_11438 {
    static FastScanner fs = new FastScanner();
    static PrintWriter pw = new PrintWriter(System.out);
    static int n, dep = 0;
    static List<List<Integer>> list = new ArrayList<>();
    static int[] depths;
    static int[][] parent;

    public static void main(String[] args) {
        n = fs.nextInt();
        depths = new int[n + 1];
        
        for (int i=0;i<=n;i++) list.add(new ArrayList<>());
        for (int i=0;i<n-1;i++){
            int a = fs.nextInt(), b = fs.nextInt();
            list.get(a).add(b);
            list.get(b).add(a);
        }

        int temp = 1;
        while (temp < n){
            dep++;
            temp *= 2;
        }
        parent = new int[n + 1][dep];

        dfs(1, 1);
        for (int i=1;i<dep;i++){
            for (int j=1;j<=n;j++){
                parent[j][i] = parent[parent[j][i - 1]][i - 1];
            }
        }

        int t = fs.nextInt();
        while (t-- > 0){
            int a = fs.nextInt(), b = fs.nextInt();
            int n1 = (depths[a] >= depths[b]) ? a : b, n2 = (depths[a] >= depths[b]) ? b : a;

            for (int i=dep-1;i>=0;i--){
                if (Math.pow(2, i) <= depths[n1] - depths[n2]){
                    n1 = parent[n1][i];
                }
            }

            for (int i=dep-1;i>=0;i--){
                if (parent[n1][i] != parent[n2][i]){
                    n1 = parent[n1][i];
                    n2 = parent[n2][i];
                }
            }
            if (n1 == n2) pw.println(n1);
            else pw.println(parent[n1][0]);
        }

        pw.close();
    }

    static void dfs(int node, int depth){
        depths[node] = depth;
        
        for (Integer i : list.get(node)){
            if (depths[i] == 0){
                dfs(i, depth + 1);
                parent[i][0] = node;
            }
        }
    }

    // ----------input function----------

    static void sort(int[] a) {
        ArrayList<Integer> L = new ArrayList<>();
        for (int i : a)
            L.add(i);
        Collections.sort(L);
        for (int i = 0; i < a.length; i++)
            a[i] = L.get(i);
    }

    static class FastScanner {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer("");

        String next() {
            while (!st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        int[] readArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        long nextLong() {
            return Long.parseLong(next());
        }
    }
}