bfs+倍增为啥会100pts+0pts呢
查看原帖
bfs+倍增为啥会100pts+0pts呢
558324
AutiFancers楼主2023/11/1 19:29
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;

const int N=500005,M=N<<1;
int n,m,S;
int h[N],e[M],ne[M],idx;
int depth[N],fa[N][16]; // 往上跳2^k步后的父亲节点

void add(int a,int b){
	e[idx]=b,ne[idx]=h[a],h[a]=idx++;	
} 

void bfs(int root){
	memset(depth,0x3f,sizeof depth);
	depth[0]=0,depth[root]=1; // depth[0]=0哨兵 
	
	queue<int> q;
	q.push(root);
	while(q.size()){
		int t=q.front();
		q.pop();
		
		for(int i=h[t];~i;i=ne[i]){
			int j=e[i];
			if(depth[j]>depth[t]+1){
				depth[j]=depth[t]+1;
				q.push(j);
				fa[j][0]=t; // j 往上跳 2^0 步后就是 t
				
				for(int k=1;k<=15;k++)
					fa[j][k]=fa[fa[j][k-1]][k-1];
			}
		}
	}
}

int lca(int a,int b){
	if(depth[a]<depth[b]) swap(a,b);
	for(int k=15;k>=0;k--)
		if(depth[fa[a][k]]>=depth[b])
			a=fa[a][k];
	
	if(a==b) return a;
	for(int k=15;k>=0;k--)
		if(fa[a][k]!=fa[b][k]){
			a=fa[a][k];
			b=fa[b][k];
		}
	return fa[a][0];
}

int main(){
	scanf("%d%d%d",&n,&m,&S);
	memset(h,-1,sizeof h);
	
	for(int i=1;i<n;i++){
		int a,b;
		scanf("%d%d",&a,&b);
		add(a,b),add(b,a);
	}
	bfs(S);
	
	while(m--){
		int a,b;
		scanf("%d%d",&a,&b);
		if(a==b) printf("%d\n",a); 
		else{
			int p=lca(a,b);
			printf("%d\n",p);
		}
	}
	
	return 0;
}
2023/11/1 19:29
加载中...