暴力70pts,但倍增后只有20玄关
查看原帖
暴力70pts,但倍增后只有20玄关
1012607
66zyq楼主2024/12/17 20:33
#include <bits/stdc++.h>
using namespace std;
vector<int> side[500010];
int father[500010][22],depth[500010];
int lg[500010];
int n,m,s;
void dfs(int now,int fa){//确定父亲 
	int i;
	depth[now] = depth[fa]+1;
	father[now][0] = fa;
	for(i=1;i<=lg[depth[i]];i++)father[now][i] = father[father[now][i-1]][i-1];
	for(i=0;i<side[now].size();i++)if(side[now][i]!=fa)dfs(side[now][i],now);
	return;
}
int lca(int x,int y){
	if(depth[x]<depth[y])swap(x,y);
	while(depth[x]>depth[y])x = father[x][lg[depth[x]-depth[y]]-1];
	if(x==y)return x;
	for(int i=lg[depth[x]]-1;i>=0;i--){
		if(father[x][i] != father[y][i]){
			x = father[x][i];
			y = father[y][i];
		}
	}
	return father[x][0];
}
int main(){
	ios::sync_with_stdio(0); 
	cin.tie(0); 
	cout.tie(0);
	int i,j;
	int x,y;
	cin>>n>>m>>s;
	for(i=1;i<n;i++){//加边 
		cin>>x>>y;
		side[x].push_back(y);
		side[y].push_back(x);
	}
	for(i=1;i<=n;i++)lg[i] = lg[i-1]/2;
	//cerr<<"Build complete!\n";
	dfs(s,0);
	//cerr<<"Progress complete!\n";
	/*for(i=1;i<=n;i++){
		for(j=0;j<=10;j++){
			cerr<<father[i][j]<<' ';
		}
		cout<<'\n';
	}*/
	//cerr<<endl;
	for(i=0;i<m;i++){
		cin>>x>>y;
		cout<<lca(x,y)<<endl;
	}
	return 0;
}
2024/12/17 20:33
加载中...