hihocoder 1067 最近公共祖先·二(tarjan LCA 离线算法O(n))

题意:LCA入门题目 = =

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <string>
#include <cstring>
#include <vector>
#include <list>
#include <queue>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
using namespace std;

#define rep(i, s, t) for(int (i)=(s);(i)<=(t);++(i))
#define urep(i, s, t) for(int (i)=(s);(i)>=(t);--(i))

typedef long long LL;

const int inf  = 0x7fffffff;
const int Maxn = (int)1e5;

struct Query {
    int v;
    int time;
};

map<string, int> id;
vector<string> name;
int tot = 0;
vector<int> g[Maxn+5];
vector<Query> query[Maxn+5];
int mark[Maxn+5];
int fa[Maxn+5];
int Rank[Maxn+5];
int ancestor[Maxn+5];
int ans[Maxn+5];

int Find(int u) {
    return u == fa[u] ? u : fa[u] = Find(fa[u]);
}

void Union(int x, int y) {
    int xRoot = Find(x), yRoot = Find(y);
    if (xRoot == yRoot) return;

    if (Rank[xRoot] >= Rank[yRoot]) {
        fa[yRoot] = xRoot;
        Rank[xRoot] += Rank[yRoot];
    }
    else {
        fa[xRoot] = yRoot;
        Rank[yRoot] += Rank[xRoot];
    }
}

void TarjanOLCA(int u) {
    fa[u] = u;
    Rank[u] = 1;
    ancestor[u] = u;
    int sz = g[u].size();
    int v;
    rep(i, 0, sz-1) {
        v = g[u][i];
        TarjanOLCA(v);
        Union(u, v);
        ancestor[Find(u)] = u;
    }
    mark[u] = 1;
    sz = query[u].size();
    rep(i, 0, sz-1) {
        Query& q = query[u][i];
        if (mark[q.v] == 1) {
            ans[q.time] = ancestor[Find(q.v)];
        }
    }
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.in", "r", stdin);
#endif
    iostream::sync_with_stdio(false);
    int n, m;
    cin >> n;
    string father_i, son_i;
    rep(i, 1, n) {
        cin >> father_i >> son_i;
        if (id.count(father_i) == 0) {
            id[father_i] = tot++;
            name.push_back(father_i);
        }
        if (id.count(son_i) == 0) {
            id[son_i] = tot++;
            name.push_back(son_i);
        }
        int fa_id = id[father_i], son_id = id[son_i];
        g[fa_id].push_back(son_id);
    }

    cin >> m;
    string x, y;
    int u, v;
    int cnt = 0;
    rep(i, 1, m) {
        cin >> x >> y;
        u = id[x];
        v = id[y];
        //cout << "read: " << x << ' ' << y << " id: " << u << ' ' << v << endl;
        query[u].push_back((Query){v, cnt});
        query[v].push_back((Query){u, cnt++});
    }

    TarjanOLCA(0);
    rep(i, 0, m-1) cout << name[ans[i]] << '\n';
    return 0;
}




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值