转化为RMQ问题也是比较常用的LCA算法之一,大多采用dfs+ST表实现,在线算法,复杂度为O(n + nlogn + Q),Q为查询次数。在线算法里,dfs+ST表算法比Doubly算法快。
算法流程:
1.对树进行dfs,将遍历到的节点按照顺序记下,将得到一个长度为2*n - 1的序列。
2.每个节点都在序列中出现,我们记录节点u第一次在序列中出现的位置为first[u]。
3.根据dfs的性质,对于两节点u、v,从first[u]遍历到first[v]的过程会经过LCA(u,v),他的深度是从min(first[u],first[v])到max(first[u],first[v])序列中最小的。
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
int n;
/