zoukankan      html  css  js  c++  java
  • 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:
    */
    
  • 相关阅读:
    Indexed DB入门导学(1)
    移动端touch事件封装
    javascript实现仿微信抢红包
    NODE学习:利用nodeJS去抓网页的信息
    ajax跨域请求无法携带cookie的问题
    四则运算
    wc
    我的问题
    css3新增加的属性
    css知识点回顾(一)
  • 原文地址:https://www.cnblogs.com/000what/p/11700299.html
Copyright © 2011-2022 走看看