板子题 WA on test #13 求调
查看原帖
板子题 WA on test #13 求调
616964
Adolfo_North楼主2023/7/30 22:16
//#pragma comment(linker, "/STACK:102400000,102400000")
#include<bits/stdc++.h>
using namespace std;
int n, m, s;
struct node{
	int to,nxt;
}e[500002*2];
int hed[500001],tot,de[500001],lg[500001],fa[500001][25];
void add(int a,int b){
	e[++tot].to=b;
	e[tot].nxt=hed[a];
	hed[a]=tot;
}
void dfs(int now,int father){
	fa[now][0]=father;
	de[now]=de[father]+1;
	for(int i=1;i<=lg[de[now]];i++) fa[now][i]=fa[fa[now][i-1]][i-1];
	for(int i=hed[now];i;i=e[i].nxt) {
		if(e[i].to!=father) dfs(e[i].to,now);
	}
}
int LCA(int x,int y){
	if(de[y]>de[x]) swap(x,y);
	while(de[x]>de[y]){
		x=fa[x][lg[de[x]-de[y]]-1];
	}
	if(x==y) return x;
	for(int i=lg[de[x]]-1;i>=0;i--) {
		if(fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i];
	}
	return fa[x][0];
}
int main(){
//	freopen("P3379_13.in","r",stdin);
//	freopen("ans.out","w",stdout);
//	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cin>>n>>m>>s;
	for(int i=1;i<n;i++){
		int a,b;
		cin>>a>>b;
		add(a,b),add(b,a);
	}
	for(int i=1;i<=n;i++) lg[i]=lg[i-1]+(1<<lg[i-1]==i); //求log(i)+1 
	dfs(s,0);
	while(m--){
		int a,b;
		cin>>a>>b;
		if(a==b) cout<<fa[a][0]<<'\n';
		else cout<<LCA(a,b)<<'\n';
	}
	return 0;
}

另:

win 11 fc 为什么会这样?

2023/7/30 22:16
加载中...