LCA Tarjan算法

LCA

LCA(Lowest Common Ancestors),即最近公共祖先,是指在有根树中,找出某两个结点u和v最近的公共祖先。
对于有根树T的两个结点u、v,最近公共祖先LCA(T,u,v)表示一个结点x,满足x是u、v的祖先且x的深度尽可能大。
另一种理解方式是把T理解为一个无向无环图,而LCA(T,u,v)即u到v的最短路上深度最小的点。
这里给出一个LCA的例子:
在这里插入图片描述
对于T=<V,E>
V={1,2,3,4,5}
E={(1,2),(1,3),(3,4),(3,5)}
则有:
LCA(T,5,2)=1
LCA(T,3,4)=3
LCA(T,4,5)=3

Tarjan

Tarjan算法是基于对图深度优先搜索的算法,每个强连通分量为搜索树中的一棵子树。搜索时,把当前搜索树中未处理的节点加入一个堆栈,回溯时可以判断栈顶到栈中的节点是否为一个强连通分量。

模板

POJ【1330】
传送门

CODE

#include <algorithm>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <list>
#include <map>
#include <iomanip>    
#include <iostream>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
const int maxn = 1e4 + 7;   
typedef long long ull;

inline int read() {
    int s = 0, w = 1;
    char ch = getchar();
    while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
    while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
    return s * w;
}

int T, n, t, a, b;
int in[maxn], fa[maxn], depth[maxn];
vector <int>m[maxn];

void dfs(int pre, int rt) {
    depth[rt] = depth[pre] + 1;
    fa[rt] = pre;
    for (int i = 0; i < m[rt].size(); ++i) {
        dfs(rt, m[rt][i]); 
    } 
}

int lca(int a, int b) {
if (depth[a] > depth[b])
        swap(a, b);
    while (depth[b] > depth[a])
        b=fa[b];
    while (a!=b)
        a=fa[a],b=fa[b];
    return a;
}

int main() {
    T = read();
    while (T--) {
        n = read();
        for (int i = 1; i <= n; ++i) m[i].clear();
        memset(in, 0, sizeof(in));
        for (int i = 1; i < n; ++i) {
            int x, y;
            x = read(), y = read();
            m[x].push_back(y);
            ++in[y];
        }
        depth[0] = -1;
        int rt = 0;
        for (int i = 1; i <= n && rt == 0; ++i) {
            if (in[i] == 0) 
                rt = i;
        }
        dfs(0, rt);
        a = read(), b = read();
        printf("%d\n", lca(a, b));
    } 
    return 0; 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值