P2814. 家谱

考点

  • 并查集

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <bits/stdc++.h>
using namespace std;
unordered_map<string, string> fa;

string find(string x) {
if (fa[x] == x) return x;
return fa[x] = find(fa[x]);
}

void join(string x, string y) {
string a = find(x), b = find(y);
fa[a] = b;
}

int main() {
char ch;
string anc, str;
while (cin >> str && (ch = str[0]) != '$') {
str = str.substr(1);
// 如果不存在这个人,就先初始化
if (!fa.count(str)) fa[str] = str;
if (ch == '#') {
anc = str;
} else if (ch == '+') {
join(str, anc);
} else {
cout << str << " " << find(str) << endl;
}
}
return 0;
}

思路

并查集的板子题,只不过从数组改用哈希表