最近公共祖先100pts但subtaskTLE求条
  • 板块灌水区
  • 楼主Guoguo2013
  • 当前回复2
  • 已保存回复2
  • 发布时间2024/12/13 23:15
  • 上次更新2024/12/14 10:51:51
查看原帖
最近公共祖先100pts但subtaskTLE求条
1070982
Guoguo2013楼主2024/12/13 23:15
#include<bits/stdc++.h>
#define int long long
#define PII pair< int, int >

using namespace std;

const int N = 1e6 + 5, mod = 998244353;
int n, q, s, h[N], e[N], ne[N], idx = 1;
int fa[N][25], dep[N]; 

template< typename T >inline void read(T &x){bool f=1;x=0;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-') f=!f;ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}x=(f?x:-x);return;}
template< typename T, typename ... L > void read(T &a , L && ... b) { read(a); read(b ...); }
int ksm(int a, int b, int p){int ans = 1;while(b){if(b & 1)ans =(ans*a)%p;b >>= 1;a = (a*a) % p;}return ans;}
void add(int u, int v){
	e[idx] = v;
	ne[idx] = h[u];
	h[u] = idx++;
}
void dfs(int u, int f){
	dep[u] = dep[f] + 1;
	fa[u][0] = f;
	for (int i = 1; i <= 20; i++) fa[u][i] = fa[fa[u][i-1]][i-1];
	for (int i = h[u]; ~i; i = ne[i]){
		int v = e[i];
		if (v == f) continue;
		dfs(v, u);
	} 
}
int LCA(int x, int y){
	if (dep[x] < dep[y]) swap(x, y);
	while (dep[x] > dep[y]) x = fa[x][0];
	if (x == y) return x;
	for (int i = 20; i >= 0; i--){
		if (fa[x][i] != fa[y][i]){
			x = fa[x][i];
			y = fa[y][i];
		}
	}
	return fa[x][0];
}
signed main(){
//	freopen("a.in", "r", stdin);
//	freopen("a.out","w",stdout);
	read(n, q, s);
	memset(h, -1, sizeof h);
	for (int i = 1; i < n; i++){
		int u, v;
		read(u, v);
		add(u, v);
		add(v, u);
	}
	dfs(s, 0);
	for (int i = 1; i <= q; i++){
		int a, b;
		read(a, b);
		printf("%lld\n", LCA(a, b));
	}
	return 0;
}
2024/12/13 23:15
加载中...