LCA的一些算法
LCA,就是求树上任意两点的最近公共祖先 (本题图片与代码均为Luogu3379) 方法我好像讲过一个,这次把主要的三个一起讲一讲 <1> 倍增(O(n log n)) 我们先考虑最基本的LCA,记录每一个点的父节点和深度。 对于两个点x,y,先将它们调到同一高度(令dep[x]>dep[y],即把x向上移(dep[x]-dep[y])步即可,然后一起往上走就可以了。 这复杂度是O(nq)的,所以在此基础上优化。 用father[i][j]表示点j向上走2^i步时的点是多少(没有就是-1),然后每次上移只要走log n次即可。 预处理的话 father[i][j]]=father[i-1][father[i-1][j]];递推即可。 CODE #include<cstdio> #include<iostream> #include<cstring> using namespace std; const int N=500005,P=25; struct data { int to,next; }e[N*2+10]; int head[N*2+10],dep[N],father[P][N],i,j,n,m,x,y,root,k; inline void read(int &x) { x=0; char ch=getchar(); while