lca:
hljs cpp">#include
#include
using
namespace
std;
const
int maxn=500001;
int n,m,gen,x,y;
struct edgeedge[2*maxn];
int deep[maxn],fa[maxn][20];//deep記錄每個點的深度,fa[i][j]:表示節點向上跳2^j 個節點所能到達的節點
//顯然fa[i][0]就是直接的父節點了
int num_edge,head[maxn];
void add_edge(int from,int to)
bool vis[maxn];
void dfs(int x)//儲存f[i][0]
for (int i=head[x]; i!=0; i=edge[i].next)
}}int lca(int x,int y)
if (x==y) return x;
for (int i=16; i>=0; i--)//因為要找最深的公共祖先,所以要倒著迴圈
}return fa[x][0];
}int main()
dfs(gen);
for (int i=1; i<=m; i++)
return0;}
/*5 5 4
3 12 4
5 11 4
2 43 2
3 51 2
4 5441
44*/
模板 最近公共祖先(LCA)
題自洛谷 如題,給定一棵有根多叉樹,請求出指定兩個點直接最近的公共祖先。輸入格式 第一行包含三個正整數n m s,分別表示樹的結點個數 詢問的個數和樹根結點的序號。接下來n 1行每行包含兩個正整數x y,表示x結點和y結點之間有一條直接連線的邊 資料保證可以構成樹 接下來m行每行包含兩個正整數a b...
最近公共祖先 LCA 模板
lca即最近公共祖先,是指 在有根樹中,找出某兩個結點u和v最近的公共祖先。時間複雜度o nlogn m n 步驟 1.將樹看作乙個無向圖,從根節點開始深搜,得到乙個遍歷序列。2.在x y區間中利用rmq演算法找到深度最小返回其下標。可以上洛谷找模板題測試 include include inclu...
最近公共祖先模板(LCA)
我們用鏈式前向星存樹。int head n 1 nex n 1 to n 1 tot 0 void add int a,int b 如果我們用fa x i 表示x的第i級祖先,那麼對時間 空間的複雜度都要求很高,資料稍微大一點顯然不行。所以我們用fa x i 表示x的第1 我們首先dfs去把整棵樹都...