求助LCA
查看原帖
求助LCA
241260
123456Mm楼主2021/7/2 22:34

求调LCA,谢谢。

只过了两个点,(输出了一堆0)

#include<bits/stdc++.h>
using namespace std;
int n,m,s;
vector<int> Adj[500010];
int Depth[500010];
bool vis[500010];
int father[500010];
int dp[500010][22];
void dfs(int u,int depth){
	Depth[u]=depth;
	for(int i=0;i<Adj[u].size();i++){
		if(!vis[Adj[u][i]]){
			vis[Adj[u][i]]=true;
			father[Adj[u][i]]=u;
			dfs(Adj[u][i],depth+1);
			vis[Adj[u][i]]=false;
		}
	}
}
void Init(){
	for(int i=1;i<=n;i++){
		if(i!=s)dp[i][0]=father[i];
	}
	for(int i=1;i<=n;i++){
		if(i==s)continue;
		for(int j=1;pow(2,j)<=Depth[i];j++)dp[i][j]=dp[dp[i][j-1]][j-1];
		
	} 
	/*for(int i=1;i<=n;i++){
		for(int j=0;pow(2,j)<=Depth[i];j++)cout<<dp[i][j]<<" ";
		cout<<endl;
	}*/
}
int main(){
	//freopen("LCA.in","r",stdin);
	cin>>n>>m>>s;
	int u,v;
	for(int i=1;i<n;i++){
		cin>>u>>v;
		Adj[u].push_back(v);
		Adj[v].push_back(u);
	}
	vis[s]=true;
	dfs(s,0);
	Init();
	//for(int i=1;i<=n;i++)cout<<Depth[i]<<" ";
	//cout<<endl;
	//for(int i=1;i<=n;i++)cout<<father[i]<<" ";
	//cout<<endl;
	int a,b;
	for(int i=1;i<=m;i++){
		cin>>a>>b;
		int x,y;
		x=a,y=b;
		if(Depth[x]>Depth[y]){
			for(int i=log2(Depth[x]);i>=0;i--){
				
				if(Depth[dp[x][i]]>=Depth[y]){
					x=dp[x][i];
				}
				if(Depth[x]==Depth[y])break;
			}
		}
		else {
			for(int i=log2(Depth[y]);i>=0;i--){
				
				if(Depth[dp[y][i]]>=Depth[x]){
					y=dp[y][i];
				}
				if(Depth[x]==Depth[y])break;
			}
		}
		//cout<<a<<" "<<b<<endl;
		if(x==y){
			cout<<x<<endl;
			continue;
		}
		for(int i=log2(Depth[x]);i>=0;i--){
			if(dp[x][i]!=dp[y][i]){
				x=dp[x][i];
				y=dp[y][i];
			}
		}
		cout<<dp[x][0]<<endl;
	}
}
2021/7/2 22:34
加载中...