求助!
查看原帖
求助!
989571
_ayaka_楼主2023/12/15 19:59

MLE加WA,MLE是DFS栈爆了,WA不知道为啥,但都不会解决

#include<bits/stdc++.h>
using namespace std;
const int maxn=500005;
struct edge {
	int to,next;
} w[maxn*2];
int h[maxn]= {0},cnt=0,d[maxn],prt[maxn]= {0},p[maxn][50],n,m,root;
void AddEdge(int x,int y) {
	w[++cnt].to=y;
	w[cnt].next=h[x];
	h[x]=cnt;
}
void DFS(int x,int deep) {
	d[x]=deep;
	for(int i=h[x]; i; i=w[i].next){
		int son=w[i].to;
//		cout<<"deep:"<<deep<<" x:"<<x<<" son:"<<son<<" prt x:"<<prt[x]<<"\n";
		if(prt[x]!=son){
//			cout<<deep<<"  "<<w[i].to<<" "<<w[i].next<<"\n";
		DFS(son,deep+1);
		}
		
	}
}
void Read() {
	int i,x,y;
	scanf("%d%d%d",&n,&m,&root);
	for(i=1; i<=n-1; i++) {
		scanf("%d%d",&x,&y);
		AddEdge(x,y);
		AddEdge(y,x);
		prt[x]=y;
	}
}
void ST() {
	int i,j;
	for(i=1; i<=n; i++)p[i][0]=prt[i];
	for(j=1; (1<<j)<=n; j++)
		for(i=1; i<=n; i++)
			p[i][j]=p[p[i][j-1]][j-1];
}
int LCA(int a,int b) {
	int k,i;
	if(d[a]<d[b])swap(a,b);
	k=int(log(d[a])/log(2));
	for(i=k; i>=0; i--)
		if(d[a]-(1<<i)>=d[b]) a=p[a][i];
	if(a==b)return b;
	for(i=k; i>=0; i--)
		if(p[a][i]!=p[b][i]) {
//			cout<<a<<" "<<p[a][i]<<"\n";
			a=p[a][i];
			b=p[b][i];
		}
	return p[a][0];
}
void Solve() {
	int i,x,y;
	for(i=1; i<=m; i++) {
		scanf("%d%d",&x,&y);
		printf("%d\n",LCA(x,y));
	}
}
int main() {
	freopen("P3379_1.in","r",stdin); 
	Read();
	DFS(root,1);
	ST();
	Solve();
	return 0;
}
2023/12/15 19:59
加载中...