70分4TLE,树链剖分求助
查看原帖
70分4TLE,树链剖分求助
638274
_YQY楼主2023/8/12 17:25
#include<bits/stdc++.h>
using namespace std;

const int N=500000;
int to[N<<1],nex[N<<1],head[N<<1],dep[N],siz[N],son[N],id[N],top[N],cnt,tot,fa[N];

void add(int x,int y){
	to[++tot]=y;
	nex[tot]=head[x];
	head[x]=tot;
}
void dfs1(int x,int f,int deep){
	fa[x]=f;
	dep[x]=deep;
	siz[x]=1;
	int maxson=-1;
	for(int i=head[x];i;i=nex[i]){
		int y=to[i];
		if(y==f) continue;
		dfs1(y,x,deep+1);
		siz[x]+=siz[y];
		if(siz[y]>maxson){
			maxson=siz[y];
			son[x]=y;
		}
	}
}
void dfs2(int x,int topf){
	//id[x]=++cnt;
//	wr[cnt]=w[x];
	top[x]=topf;
	if(!son[x]) return ;
	dfs2(son[x],topf);
	for(int i=head[x];i;i=nex[i]){
		int y=to[i];
		if(y==fa[x]||y==son[x])
			continue;
		dfs2(y,y);
	}
}
int lca(int a,int b)
{
    while(top[a]!=top[b])
    {
        if(dep[top[a]]>dep[top[b]]) a=fa[top[a]];
        else b=fa[top[b]];
    }
    if(dep[a]<dep[b]) return a;
    else return b;
}

int n,m,s;
int main(){
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cin>>n>>m>>s;
	for(int i=1;i<n;i++){ 
		int u,v;
		cin>>u>>v;
		add(u,v);
		add(v,u);
	}
	dfs1(s,0,0);
	dfs2(s,0);
	for(int i=1;i<=m;i++){
		int u,v;
		cin>>u>>v;
		cout<<lca(u,v)<<endl;
	}
}
2023/8/12 17:25
加载中...