Hihocoder 1062 common ancestor 1

Meaning of the questions: given N pieces of parent-child relationship, ask the M two recent common ancestor, there is no output to -1
Analysis:
Mapping father with a map for each son,
began to look for the most recent common ancestor, the first person to go first ancestors All ancestors are marked;
then start looking for the second person, if found to be labeled, is their most recent common ancestor, output,
if the second person to find ancestors finish but could not find, there is no common ancestor, output - 1

/**/
#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;

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;
int n, m;
string a, b;
map<string, string> fa;

void Run(string a, string b)
{
    map<string, bool> vis;
    vis[a] = 1;
    while(fa[a].size()) {
        vis[fa[a]] = 1;
        a = fa[a];
    }
    while(b.size()) {
        if(vis[b]) { cout << b << "\n"; return ;}
        b = fa[b];
    }
    puts("-1");
}

int main()
{
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    scanf("%d", &n);
    while(n--) {
        cin >> a >> b;
        fa[b] = a;
    }
    scanf("%d", &m);
    while(m--) {
        cin >> a >> b;
        Run(a, b);
    }

    return 0;
}
/*
    input:
    output:
    modeling:
    methods:
    complexity:
    summary:
*/

Guess you like

Origin www.cnblogs.com/000what/p/11666714.html