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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值