1. 程式人生 > >【LCA】Tarjan離線演算法(並查集+dfs)模板

【LCA】Tarjan離線演算法(並查集+dfs)模板

vector <int> Q[N];

int Find(int x)
{
    if(x != fa[x]) return fa[x] = Find(fa[x]);
    return x;
}

void Union(int x, int y)
{
    int fx = Find(x), fy = Find(y);
    if(fy != fx) fa[fy] = fx;
}

void dfs(int u)
{
    anc[u] = u;
    for(int i = head[u]; ~i; i = e[i].next) {
        int v = e[i].v;
        dfs(v);
        Union(u, v);
        anc[Find(u)] = u;
    }
    vis[u] = true
; int sz = Q[u].size(); for(int i = 0; i < sz; i++) { int v = Q[u][i]; if(vis[v]) { printf("%d\n", anc[Find(v)]); return ; } } }