• Hihocoder 1067


    最近公共祖先二 离线算法

    /**/
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <cctype>
    #include <iostream>
    #include <algorithm>
    #include <map>
    #include <set>
    #include <vector>
    #include <string>
    #include <stack>
    #include <queue>
    
    typedef long long LL;
    typedef unsigned long long ULL;
    using namespace std;
    typedef pair<int, int> P;
    #define x first
    #define y second
    #define pb push_back
    bool Sqrt(LL n) { return (LL)sqrt(n) * sqrt(n) == n; }
    const double PI = acos(-1.0), ESP = 1e-10;
    const LL INF = 99999999999999;
    const int inf = 999999999, N = 1e5 + 24;
    vector<int> G[N];
    vector<P> Q[N];
    map<string, int> H;
    string a, b, m[N];
    int A, B, fa[N], n, k, c, ans[N];
    int fnd(int x) { return x == fa[x] ? x : fa[x] = fnd(fa[x]); }
    void dfs(int u, int p)
    {
        fa[u] = u;
        for(auto v : G[u]) if(v != p) dfs(v, u);
        for(auto v : Q[u]) if(fa[v.x]) ans[v.y] = fnd(v.x);
        fa[u] = p;
    }
    
    int main()
    {
        //freopen("in.txt", "r", stdin);
        //freopen("out.txt", "w", stdout);
        scanf("%d", &n);
        while(n--) {
            cin >> a >> b;
            if(!(A = H[a])) { A = H[a] = ++c; m[c] = a;}
            if(!(B = H[b])) { B = H[b] = ++c; m[c] = b;}
            G[A].pb(B); G[B].pb(A);
        }
        scanf("%d", &k);
        for(int i = 1; i <= k; i++) {
            cin >> a >> b;
            A = H[a]; B = H[b];
            Q[A].pb(P(B, i)); Q[B].pb(P(A, i));
        }
        dfs(1, 0);
        for(int i = 1; i <= k; i++) cout << m[ans[i]] << "
    ";
    
        return 0;
    }
    /*
        input:
        output:
        modeling:
        methods:
        complexity:
        summary:
    */
    
  • 相关阅读:
    csu 1513 Kick the ball! 搜索
    训练赛bug总结
    csu 1780 简单的图论问题? 搜索
    贪吃蛇
    hdu 1541 Stars 树状数组
    FZU 2092 收集水晶 BFS记忆化搜索
    [ An Ac a Day ^_^ ] UVALive 2035 The Monocycle BFS
    52. N皇后 II
    修改全局变量-global 修改外部嵌套函数中的变量 nonlocal
    安装glove 不报错
  • 原文地址:https://www.cnblogs.com/000what/p/11700299.html
Copyright © 2020-2023  润新知