MLE 2 9 10 求助
查看原帖
MLE 2 9 10 求助
120438
Lacrymabre楼主2020/12/16 21:36
#include<iostream>
#include<cstdio>
#include<iomanip>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<set>
#define ll long long
#define N 500000
using namespace std;

inline long long read()
{
    ll f=1,s=0;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')s=(s<<1)+(s<<3)+ch-'0',ch=getchar();
    return s*f;
}

ll n,m,s,x,y;
ll dep[500100];
ll f[500100][1919],lg[21];
ll from[N*2],net[N*2],to[N*2],cnt;

inline void add(ll x,ll y){
	to[++cnt]=y;
	net[cnt]=from[x];
	from[x]=cnt;
}

void relog(){
	for(int j=1;j<16;j++)
		for(int i=1;i<=n;i++)
			f[i][j]=f[f[i][j-1]][j-1];
}

void dfs(ll now,ll fa){
	f[now][0]=fa;dep[now]=dep[fa]+1;
	for(int i=from[now];i;i=net[i]) if(to[i]!=fa) dfs(to[i],now);
}

ll LCA(ll x,ll y){
	if(dep[x]<dep[y]) swap(x,y);
	while(dep[x]>dep[y])
		x=f[x][lg[dep[x]-dep[y]]-1];
	if(x==y) return x;
	for(int i=15;i>=0;i--)
		if(f[x][i]!=f[y][i])
			x=f[x][i],y=f[y][i];
	return f[x][0];
}

int main(){
	n=read();m=read();s=read();
	for(int i=1;i<n;i++){
		x=read();y=read();
		add(x,y);add(y,x);
	}
	for(int i=1;i<=n;i++) lg[i]=lg[i>>1]+1;
	dfs(s,0);
	relog();
	while(m-->0){
		x=read();y=read();
		cout<<LCA(x,y)<<"\n";
	}
	return 0;
} 
2020/12/16 21:36
加载中...