hihoCoder week13 最近公共祖先·一

用的dfs,自下往上搜索一个节点的所有祖先,然后在相应祖先 判断是否是另一个节点的祖先,如果是 就截止,否则继续往上搜索,直到搜索到,或者知道所有的祖先都被扫描完成

#include <bits/stdc++.h>
using namespace std;
const int N = 1e3+10;

int n;
int cnt, tot;
map<string ,int> mp;
string s[N];

vector<int> son[N], fa[N];
string s1, s2;

int getId(string str)
{
    if(mp[str]) {
        return mp[str];
    }
    mp[str] = (++cnt);
    s[cnt] = str;
    return cnt;
}

int dfs(int u, int v) {
    if(u == v) return true;
    for(int i=0; i<son[u].size(); i++) {
        int x = son[u][i];
        //cout << s[x] <<" ";
        if(dfs(son[u][i], v)) {
            return true;
        }
    }
    //cout<<"
";
    return false;
}

int main()
{
    freopen("in.txt","r",stdin);
    scanf("%d", &n);
    for(int i=1; i<=n; i++) {
        cin >> s1 >> s2;
        int u = getId(s1);
        int v = getId(s2);
        son[u].push_back(v);
        fa[v].push_back(u);
    }
    int m; scanf("%d",&m);
    while(m--) {
        cin >> s1 >> s2;
        int u = getId(s1);
        int v = getId(s2);
        // cout <<u <<" "<< v<<"
";
        bool flag=0;
        queue<int> que;
        que.push(u);
        while(!que.empty()) {
            int tmp=que.front(); que.pop();
            //cout << s[tmp]<<"
";
            for(int i=0; i<fa[tmp].size(); i++) {
                que.push(fa[tmp][i]);
            }
            if(dfs(tmp,v)) {
                flag = true;
                cout << s[tmp] <<endl;
                break;
            }
        }
        if(!flag) 
            puts("-1");
        
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Draymonder/p/10007484.html