#include <bits/stdc++.h>
using namespace std;
#define N 50005 // 最大点数
map<string, string> fa;//fa[儿子]:父亲
string find(string x) // 查找祖先
{
if(fa[x] == x) // 找到集合代表元
return x;
else
return fa[x] = find(fa[x]); // 路径压缩
}
int main()
{
char c;
string father, child;
while(cin >> c && c != '$') // 输入未结束
{
if(c == '#') // 初始化一个集合
{
cin >> father;
if(fa.count(father) == 0) // 不存在该集合代表元
fa[father] = father;
}
else if(c == '+') // 合并集合
{
cin >> child;
fa[child] = father;
}
else if(c == '?') // 查询集合代表元
{
cin >> child;
cout << child << ' ' << find(child) << endl;
}
}
return 0;
}
问题 F: 家谱
最新推荐文章于 2025-05-28 22:18:33 发布