Problem Solving/BOJ [백준 11438번] [LCA] LCA 2 - 728x90 반응형 Approach 전형적인 LCA 문제 Code #include <bits/stdc++.h> #define fastio cin.tie(0)->sync_with_stdio(0) using namespace std; using ll = long long; using pii = pair<int, int>; int move_x[4] = {-1, 1, 0, 0}; int move_y[4] = {0, 0, -1, 1}; const int MAX = 18; vector<int> adj[100001]; int parent[100001][18]; int depth[100001]; bool visited[100001]; void dfs(int cur, int cur_depth){ visited[cur] = 1; depth[cur] = cur_depth; for(auto &p : adj[cur]){ if(!visited[p]){ parent[p][0] = cur; dfs(p, cur_depth + 1); } } } int main() { fastio; memset(visited, 0, sizeof(visited)); memset(parent, -1, sizeof(parent)); int n; cin >> n; for(int i = 0; i < n - 1; i++){ int a, b; cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); } dfs(1, 0); for(int j = 1; j < MAX; j++){ for(int i = 2; i <= n; i++){ if(parent[i][j - 1] != -1){ parent[i][j] = parent[parent[i][j - 1]][j - 1]; } } } // Query int m; cin >> m; for(int i = 0; i < m; i++){ int u, v; cin >> u >> v; if(depth[u] < depth[v]) swap(u, v); int diff = depth[u] - depth[v]; for(int j = 0; diff; j++){ if(diff % 2) u = parent[u][j]; diff /= 2; } if(u != v){ for(int j = MAX - 1; j >= 0; j--){ if(parent[u][j] != -1 && parent[u][j] != parent[v][j]){ u = parent[u][j]; v = parent[v][j]; } } u = parent[u][0]; } cout << u << "\n"; } return 0; } 반응형 공유하기 URL 복사카카오톡 공유페이스북 공유엑스 공유 게시글 관리 구독하기비룡의 컴퓨터이야기 Contents Approach Code 당신이 좋아할만한 콘텐츠 [백준 10538번] [Rabin-karp] 빅 픽쳐 2022.02.09 [백준 1786번] [KMP] 찾기 2022.02.08 [백준 14938번] [Dijkstra] 서강그라운드 2022.01.15 [백준 11779번] [Dijkstra] 최소비용 구하기 2 2022.01.15 댓글 0 + 이전 댓글 더보기