LCA求优化
  • 板块灌水区
  • 楼主huanxue
  • 当前回复6
  • 已保存回复6
  • 发布时间2025/1/21 15:26
  • 上次更新2025/1/21 17:16:54
查看原帖
LCA求优化
929086
huanxue楼主2025/1/21 15:26
#include <bits/stdc++.h>
using namespace std;
int bz[500005][25] , fa[500005][25];
vector <int> edge[500005];
int dep[500005];
int n , m , s;
inline int read(){
	char c = getchar_unlocked();
	int f = 1 , x = 0;
	while(c < '0' || c > '9'){
		if(c == '-') f = -f;
		c = getchar_unlocked();
	}
	while(c >= '0' && c <= '9'){
		x = x * 10 + c - '0';
		c = getchar_unlocked();
	}
	return x * f;
} 
void dfs(int x , int y){
    int len = edge[x].size();
    dep[x] = dep[y] + 1;
    bz[x][0] = y;
    for(int i = 1 ; i <= 19 ; i++){
        bz[x][i] = bz[bz[x][i - 1]][i - 1];
    }
    for(int i = 0 ; i <= len - 1 ; i++){
        int ny = edge[x][i];
        if(ny != y) dfs(ny , x);
    }
    return;
}
int LCA(int a , int b){
    if(dep[a] < dep[b]) swap(a , b);
    for(int i = 19 ; i >= 0 ; i--){
        if(dep[bz[a][i]] >= dep[b]) a = bz[a][i];
    }
    if(a == b) return a;
    for(int i = 19 ; i >= 0 ; i--){
        if(bz[a][i] != bz[b][i]) a = bz[a][i] , b = bz[b][i];
    }
    return bz[a][0];
}
int main(){
    n = read() , m = read() , s = read();
    for(int i = 1 ; i <= n - 1 ; i++){
        int u , v;
        u = read() , v = read();
        edge[u].push_back(v);
        edge[v].push_back(u);
    }
    dfs(s , 0);
    while(m--){
        int a , b;
        a = read() , b = read();
        cout << LCA(a , b) << endl;
    }
    return 0;
}
2025/1/21 15:26
加载中...