30pts全TLE求助!!!
查看原帖
30pts全TLE求助!!!
730717
wanwang楼主2023/8/25 17:28
#include<bits/stdc++.h>
#define maxm 5000005
using namespace std;
namespace IO{
	char ibuf[(1<<20)+1],*iS,*iT;
	#if ONLINE_JUDGE
	#define gh() (iS==iT?iT=(iS=ibuf)+fread(ibuf,1,(1<<20)+1,stdin),(iS==iT?EOF:*iS++):*iS++)
 	#else
	#define gh() getchar()
	#endif
	inline long long read(){
		char ch=gh();
		long long x=0;
		bool t=0;
		while(ch<'0'||ch>'9')   t|=ch=='-',ch=gh();
		while(ch>='0'&&ch<='9') x=x*10+(ch^48),ch=gh();
		return t?-x:x;
	}
	inline char getc(){
		char ch=gh();
		while(ch<'a'||ch>'z') ch=gh();
		return ch;
	}
}
using IO::read;//可获取标准输入中下一个未被读入的 64 位有符号整数。
using IO::getc;//可获取标准输入中下一个未被读入的小写字母。
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;
	for(int i=1;pow(2,i)<=depth[now];i++)
		f[now][i]=f[f[now][i-1]][i-1];
	for(int i=head[now];i;i=a[i].u){
		int p=a[i].v;
		if(p==fa)continue;
		f[p][0]=now;
		dfs(p,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]){
			x=f[x][i];
			y=f[y][i];
		}
	return f[x][0];
}
int main(){
	n=read();
	m=read();
	s=read();
	t=log2(n)+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)cout<<a;
		else cout<<lca(a,b)<<"\n";
	}
	return 0;
}
/*
5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5
*/

改了一个下午了,有没有大佬来救救

2023/8/25 17:28
加载中...