程序如下:
#include <cstdio>
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <map>
using namespace std;
//父节点或祖先节点
map<string, string> fa;
//并查集
string Find(string x){
if(fa[x]==x) return x;
else return fa[x]=Find(fa[x]); //路径压缩
}
//合并
void Union(string child, string father){
fa[child] = father;
}
int main(){
string cfa;
while(true){
char ch = getchar();
if(ch == '#'){ //父节点
string tmp;
cin>>tmp;
cfa = tmp;
}else if(ch == '+'){ //子节点
string tmp;
cin>>tmp;
Union(tmp,cfa);
}else if(ch == '?'){ //查询是否在同一的集合中
string tmp;
cin>>tmp;
cout<<tmp<<" "<<Find(tmp)<<endl;
}else if(ch == '$') break;
}
return 0;
}
样例运行如下:
#George
+Rodney
#Arthur
+Gareth
+Walter
#Gareth
+Edward
?Edward
Edward <-这是输出
?Walter
Walter <-这是输出
?Rodney
Rodney <-这是输出
?Arthur
Arthur <-这是输出
$