30pts全T求救
查看原帖
30pts全T求救
730717
wanwang楼主2023/10/7 18:54

翻遍了题解都找不到我的怎么错了。

#include<bits/stdc++.h>
#define maxm 5000005
using namespace std;
inline int read(){
	int XX=0,FF=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){
		if(ch=='-')
			FF*=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		XX=XX*10+ch-48;
		ch=getchar();
	}
	return XX*FF;
}
inline void write(int x){
	if(x<0){
		putchar('-');
		x=-x;
	}
	if(x>9)
		write(x/10);
	putchar(x%10+'0');
}
int n,m,s,t,tot;
int f[maxm][22],head[maxm],depth[maxm];
struct edge{
	int u,v;
}a[maxm];
void add(int x,int y){
	tot++;
	a[tot].u=head[x];
	a[tot].v=y;
	head[x]=tot;
	a[++tot].u=head[y];
	a[tot].v=x;
	head[y]=tot;
}
void dfs(int now,int fa){
	depth[now]=depth[fa]+1;
	f[now][0]=fa;
	for(int i=1;i<=t;i++){
		if(depth[now]<=(1<<i))break;
		f[now][i]=f[f[now][i-1]][i-1];
	}
	for(int i=head[now];i;i=a[i].u)
		if(a[i].v!=fa)dfs(a[i].v,now);
}
int lca(int x,int y){
	if(depth[x]<depth[y])swap(x,y);
	for(int i=t;i>=0;i--){
		if(depth[f[x][i]]>=depth[y])x=f[x][i];
	}
	if(x==y)return x;
	for(int i=t;i>=0;i--)
		if(f[x][i]!=f[y][i]&&depth[f[x][i]]){
			x=f[x][i];
			y=f[y][i];
		}
	return f[x][0];
}
int main(){
	n=read();
	m=read();
	s=read();
	memset(f,-1,sizeof(f));
	t=log(n)/log(2)+1;
	for(int i=1;i<n;i++){
		int u=read(),v=read();
		add(u,v);
		add(v,u);
	}
	dfs(s,0);
	for(int i=1;i<=m;i++){
		int a=read(),b=read();
		if(a==b)write(a);
		else write(lca(a,b)),puts("");
	}
	return 0;
}
/*
5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5
*/
2023/10/7 18:54
加载中...