hihoCoder#1062 最近公共祖先·

原题地址

A和A的共同祖先是A,即使A没有在之前的家谱中出现过!被这个坑了,WA了很久。。。

比如:小头爸爸是大头儿子他爹,问:隔壁王叔叔和隔壁王叔叔的最近祖先是谁?,答:隔壁王叔叔。

代码:

 1 #include <iostream>
 2 #include <map>
 3 #include <set>
 4 #include <string>
 5 
 6 using namespace std;
 7 
 8 int main() {
 9   int N, M;
10   map<string, string> f;
11 
12   cin >> N;
13   for (int i = 1; i <= N; i++) {
14     string father, child;
15     cin >> father >> child;
16     f[child] = father;
17   }
18   cin >> M;
19   while (M--) {
20     string a, b;
21     string ancestor = "-1";
22     set<string> visited;
23     cin >> a >> b;
24     while (!a.empty()) {
25       visited.insert(a);
26       a = f[a];
27     }
28     while (!b.empty()) {
29       if (visited.find(b) != visited.end()) {
30         ancestor = b;
31         break;
32       }
33       b = f[b];
34     }
35     cout << ancestor << endl;
36   }
37 
38   return 0;
39 }
原文地址:https://www.cnblogs.com/boring09/p/4376228.html