树链剖分求调(样例都过不了)
查看原帖
树链剖分求调(样例都过不了)
538899
jia_hua_wu楼主2022/11/8 13:30

rt

#include<bits/stdc++.h>
#define rint register int
using namespace std;
const int N = 500005;
int n,m,s;

struct start{
	int to,ne;
}edg[N*2];
int head[N],cnt=1;

inline void add(int x,int y){
	edg[cnt].ne = head[x];
	edg[cnt].to = y;
	head[x] = ++cnt;
} 

int son[N],fa[N];
int dep[N],top[N],siz[N];

void dfs1(int x){
    dep[x]=dep[fa[x]]+1;
    siz[x]=1;
    
    int maxson=-1;
    for(rint i=head[x];i;i=edg[i].ne){
        int y=edg[i].to;
        if(y==fa[x])continue;
        
        fa[y] = x;
        dfs1(y); 
        siz[x]+=siz[y];
        if(siz[y]>maxson) son[x]=y,maxson=siz[y]; 
    }
}

void dfs2(int x,int topf){ 
    top[x]=topf; 
    
    if(!son[x])return; 
    
	dfs2(son[x],topf); 
    for(rint i=head[x];i;i=edg[i].ne){
        int y=edg[i].to;
        if(y==fa[x] || y==son[x])continue;
        dfs2(y,y); 
    }
}

inline int LCA(int x,int y){	
	while(top[x] != top[y]){
		if(dep[top[x]] > dep[top[y]]) x = fa[top[x]];
		else y = fa[top[y]];
	}
	
	return (dep[x] > dep[y])? y : x;
}

int main(){
	scanf("%d %d %d",&n,&m,&s);
	for(rint i=1;i<n;i++){
		int x,y;
		scanf("%d %d",&x,&y);
		add(x,y);
		add(y,x);
	}
	
	dfs1(s);
	dfs2(s,s);
	for(rint i=1;i<=m;i++){
		int x,y;
		scanf("%d %d",&x,&y);
		printf("%d\n",LCA(x,y));
	}
	return 0;
} 
2022/11/8 13:30
加载中...