[백준] BOJ 3584

SONGB·2023년 6월 9일
0

알고

목록 보기
1/12

문제

BOJ 3584 가장 가까운 공통 조상

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

코드

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

	static int []parent;
	static int []level;
	static ArrayList<Integer>[]tree;
	
	public static void main(String[] args)throws Exception {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		
		int tc=Integer.parseInt(br.readLine());
		
		for(int t=1;t<=tc;t++) {
			int n=Integer.parseInt(br.readLine());
			
			tree=new ArrayList[n+1];
			parent=new int[n+1];
			level=new int[n+1];
			
			for(int i=1;i<=n;i++) {
				tree[i]=new ArrayList<>();
			}
			
			boolean[] check=new boolean[n+1];
			Arrays.fill(check, true);
			
			StringTokenizer st;
			
			for(int i=1;i<n;i++) {
				st=new StringTokenizer(br.readLine());
				int p=Integer.parseInt(st.nextToken());
				int d=Integer.parseInt(st.nextToken());
				
				tree[p].add(d);
				check[d]=false;
			}
			
			int idx=0;
			for(int i=1;i<n+1;i++) {
				if(check[i]) {
					idx=i;
					break;
				}
			}
			
			init(idx,1,0);
			
			st = new StringTokenizer(br.readLine());
			int a = Integer.parseInt(st.nextToken());
			int b = Integer.parseInt(st.nextToken());
			
			System.out.println(lca(a, b));
			
		}

	}
	
	static void init(int cur,int height,int p) {
		level[cur]=height;
		parent[cur]=p;
		for(int a:tree[cur]) {
			if(a!=p) {
				init(a,height+1,cur);
			}
		}
	}
	
	static int lca(int a,int b) {
		int ah=level[a];
		int bh=level[b];
		while(ah>bh) {
			a=parent[a];
			ah--;
		}
		while(ah<bh) {
			b=parent[b];
			bh--;
		}
		while(a!=b) {
			a=parent[a];
			b=parent[b];
		}
		return a;
	}
}
profile
⚽⚾데굴데굴 굴러가는 내 맘대로 벨로그🏀🏐

0개의 댓글