怀疑题目数据过水(有可能是我自己的问题)
查看原帖
怀疑题目数据过水(有可能是我自己的问题)
443642
一只小可爱吖楼主2021/7/19 15:18

满分代码:

#include<bits/stdc++.h>
using namespace std;
int n,m,s,num;
int dp[500002],h[500002],power[500002],fa[500002][22];
struct tree{
	int to,next;
}e[1000000];
void cb(int from,int to){
	num++;
	e[num].to=to;
	e[num].next=h[from];
	h[from]=num;
}
void an(int u,int f){
	dp[u]=dp[f]+1;
	fa[u][0]=f;
	for(int i=1;i<=power[dp[u]];i++)
		fa[u][i]=fa[fa[u][i-1]][i-1];
	for(int i=h[u];i;i=e[i].next)
		if(e[i].to!=f)
			an(e[i].to,u);
}
int LCA(int x,int y){
	if(dp[x]<dp[y]){
		int u=x;
		x=y;
		y=u;
	}
	while(dp[x]>dp[y])
		x=fa[x][power[(dp[x]-dp[y])]-1];
	if(x==y)
		return y;
	for(int i=power[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(){
	scanf("%d%d%d",&n,&m,&s);
	for(int i=1;i<=n-1;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		cb(x,y);
		cb(y,x);
	}
	for(int i=1;i<=n;i++)
		power[i]=power[i-1]+(1<<power[i-1]==i);
	an(s,0);
	for(int i=1;i<=m;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		cout<<LCA(x,y)<<endl;
	}
	return 0;
} 

在代码33行处,即LCA函数for循环处

i=power[x]-1

是错误的,正确的如下

i=power[dp[x]]-1

这个错误在这道题里面没有影响,但是在P3398中就必须用第二种,也许是我的问题,还请多多指教

2021/7/19 15:18
加载中...