题解疑似存在问题
查看原帖
题解疑似存在问题
484719
XSJProgrammer楼主2023/7/31 15:46

下载了Subtask1 #1 数据,题解无一例外tle+re 也许我这电脑有问题? 顺便求调后四个点tle的代码:

#include<bits/stdc++.h>
#define MAXN 5000010
using namespace std;
int n,q,root;
int lg[MAXN];
void initlg(){
	lg[0]=0;
	lg[1]=0;
	for(int i=0;i<n;i++)lg[i]=lg[i/2]+1;
}
struct eg{
	int val,to;
}edge[2*MAXN];
int tot,head[2*MAXN];
void add(int x,int y){
	edge[++tot].val=y;
	edge[tot].to=head[x];
	head[x]=tot;
	edge[++tot].val=x;
	edge[tot].to=head[y];
	head[y]=tot;
}
int f[MAXN][30];//f[i][j] means i's (2^j)th father
int depth[MAXN];
void dfs(int rt,int now){
	depth[now]=depth[rt]+1;
	f[now][0]=rt;
	for(int i=1;i<=lg[depth[now]];i++)f[now][i]=f[f[now][i-1]][i-1];
	for(int i=head[now];i;i=edge[i].to){
		if(edge[i].val!=rt)dfs(now,edge[i].val); 
	}
}
int lca(int a_,int b_){
	int a=a_,b=b_;
	if(depth[a]>depth[b])swap(a,b);
	while(depth[b]>depth[a])b=f[b][0];
	if(a==b)return a;
	int i=lg[depth[a]];
	for(;i>=0;i--){
		if(f[a][i]!=f[b][i]){
			a=f[a][i];
			b=f[b][i];
		}
	}
	return f[a][0];
}
int main(){
	freopen("q.txt","r",stdin);
	ios::sync_with_stdio(0);
	cin>>n>>q>>root;
	initlg();
	for(int i=1;i<n;i++){
		int a,b;
		cin>>a>>b;
		add(a,b);
	}
	dfs(0,root);
	while(q--){
		int a,b;
		cin>>a>>b;
		cout<<lca(a,b)<<endl;
	}
}
2023/7/31 15:46
加载中...