Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
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
Tags
more
Archives
Today
Total
관리 메뉴

코드와이

[BAEKJOON] 11437. LCA 본문

acmicpc

[BAEKJOON] 11437. LCA

코드와이 2021. 12. 1. 15:12

 

문제링크

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

 

11437번: LCA

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

www.acmicpc.net

 

package acmicpc.Gold3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;

public class LCA {

	static int n, parent[], depth[];
	static List<Integer>[] list;
	public static void main(String[] args) throws NumberFormatException, IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		StringBuilder sb = new StringBuilder();
		
		n = Integer.parseInt(br.readLine());
		parent = new int[n + 1];
		depth = new int[n + 1];
		list = new ArrayList[n + 1];			// node 별로 부모 노드의 수를 입력시킬 배열
		
		for(int i = 1 ; i <= n ; i++) {
			list[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());

			list[a].add(b);
			list[b].add(a);
			
		}
		
		// depth와 parent를 설정
		dfs(1,1);
		
		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());
			
			sb.append(findParent(a,b)).append("\n");
		}
		
		sb.setLength(sb.length() - 1);
		System.out.println(sb);
		
	}
	
	public static void dfs(int node, int d) {
		
		depth[node] = d++;
		for(int x : list[node]) {
			if(depth[x] == 0) {
				dfs(x, d);
				parent[x] = node;
			}
		}
	}
	
	public static int findParent(int a, int b) {		
		
		if(depth[a] > depth[b]) {
			while(depth[a] != depth[b]) {
				a = parent[a];
			}
		} else if(depth[a] < depth[b]) {
			while(depth[a] != depth[b]) {
				b = parent[b];
			}
		}
		
		while(a != b) {
			a = parent[a];
			b = parent[b];
		}
		
		return a;
	}
}

'acmicpc' 카테고리의 다른 글

[BAEKJOON] 11779. 최소비용구하기2  (0) 2021.12.10
[BAEKJOON] 16637. 괄호 추가하기  (0) 2021.12.06
[BAEKJOON] 2437. 저울  (0) 2021.11.23
[BAEKJOON] 1300. K번째 수  (0) 2021.11.06
[BAEKJOON] 2263. 트리의 순회  (0) 2021.11.06