蒟蒻求调
查看原帖
蒟蒻求调
653241
JYZ_huracan楼主2023/11/4 08:45

样例没过(lca模板啊)

#include <bits/stdc++.h>
using namespace std;
const int N=500010;
const int M_bit=32;
int n,m,s;
struct node{
	int next;
	int t;
}edge[N<<1];
int f[N][M_bit],pos;
int head[N],deep[N];
void add(int x,int y){
	edge[++pos].t=y;
	edge[pos].next=head[x];
	head[x]=pos;
}
void dfs(int u,int father){
	deep[u]=deep[father]+1;
	f[u][0]=father;
	for(int i=0;i<M_bit;i++){
		f[u][i+1]=f[f[u][i]][i];
	}
	for(int i=head[u];i!=0;i=edge[i].next){
		int v=edge[i].t;
		if(v!=father) dfs(v,u);
		
	}
}
int main()
{
	ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m>>s;
    for(int i=1;i<n;i++){
    	int s1,s2;
    	cin>>s1>>s2;
    	add(s1,s2);
    	add(s2,s1);
	}
	dfs(s,0);
	while(m--){
		int x,y;
		bool flag=false;
		cin>>x>>y;
		cout<<x<<' '<<y<<' '<<deep[x]<<' '<<deep[y]<<' '<<'\n';
		if(deep[x]>deep[y]) swap(x,y);
		if(deep[x]!=deep[y]){
			for(int i=M_bit;i>=0;i--){
				if(deep[f[y][i]]>=deep[x]) y=f[y][i];
				if(x==y) {
					cout<<x<<'\n';
					flag=1;
					break;
				}
			}
		}
		if(flag) continue;
		for(int i=M_bit;i>=0;i--){
			if(f[x][i]!=f[y][i]){
				x=f[x][i];
				y=f[y][i];
			}
			if(f[x][0]==f[y][0]){
				cout<<f[x][0]<<'\n';
				break;
   			}
		}
	}
	return 0;
}

2023/11/4 08:45
加载中...