这题卡树剖?
查看原帖
这题卡树剖?
366254
dxy2020楼主2022/5/22 11:21

rt,TLE on #11,求卡常

#include <bits/stdc++.h>
using namespace std;
const int N=500000+5;
inline void in (int &x){
	x=0;char c=getchar();
	while (c>'9'||c<'0') c=getchar();
	while (c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
}
int n,m,root,u,v,cnt;
int son[N],sz[N],dep[N],fa[N],top[N],head[N];
struct Edge{
	int to,next;
}E[N<<1];
inline void Add (int u,int v){
	E[++cnt].to=v;
	E[cnt].next=head[u];
	head[u]=cnt;
}
inline void dfs1 (int u,int f,int depth){
	son[u]=0;sz[u]=1;dep[u]=depth;fa[u]=f;
	for (int i=head[u];i;i=E[i].next){
		int v=E[i].to;
		if (v==fa[u]) continue ;
		dfs1 (v,u,depth+1);
		sz[v]+=sz[u];
		if (sz[v]>sz[son[u]]) son[u]=v;
	}
}
inline void dfs2 (int u,int pa){
	top[u]=pa;
	if (son[u]) dfs2 (son[u],pa);
	for (int i=head[u];i;i=E[i].next){
		int v=E[i].to;
		if (v!=fa[u]&&v!=son[u]) dfs2 (v,v);
	}
}
inline int LCA (int x,int y){
	while (top[x]!=top[y]){
		if (dep[top[x]]<dep[top[y]]) swap (x,y);
		x=fa[top[x]];
	}
	if (dep[x]>dep[y]) swap (x,y);
	return x;
}
signed main (){
	in (n);in (m);in (root);
	for (int i=1;i<n;++i){
		in (u);in (v);
		Add (u,v);Add (v,u);
	}
	dfs1 (root,root,1);dfs2 (root,root);
	for (int i=1;i<=m;++i){
		in (u);in (v);
		printf ("%d\n",LCA (u,v));
	}
	return 0;
}
2022/5/22 11:21
加载中...