这个方法求LCA可以O1查询。
而且会有一些神奇的性质:
st[x]<st[y]<=ed[y]<=ed[x],表示x是y的祖先。st是第一次访问节点的时间,ed是最后一次访问节点的时间
两个节点的LCA等于min(st[x],ed[y])中间dfs序最小的那个节点。//也可以写成min(st[x],st[y]),min(ed[x],st[y]),min(ed[x],ed[y])
因为先访问x,然后会遍历x的子树,这里面肯定没x的祖先。
然后会往上回溯,直到x和y 的LCA,然后会往下遍历,遍历到y,dfs序最小的一定刚好是xy的LCA,因为最多回溯到这里,否则会跳过y,与dfs序遍历规则矛盾。
由这个我们可以推出:多个点的LCA,等于min(min(st[i]),max(st[j])),即这些点中,dfs序最小的点与dfs序最大的点的LCA。
这是个很神奇的性质,由这个性质我们可以做出一道题。。。网上竟然没人说这个性质,。。
#include<bits/stdc++.h>
using namespace std;
const int M =1e6+7;
int head[M],cnt;
void init(){cnt=0,memset(head,0,sizeof(head));}
struct EDGE{int to,nxt,val;}ee[M*2];
void add(int x,int y){ee[++cnt].nxt=head[x],ee[cnt].to=y,head[x]=cnt;}
int st[M],ed[M],dep[M],lg[M],dp[M][20];
int euler[