查询祖先的题目,自然是要用到并查集了,不过在输入,数据的处理上要注意细节,名字的前面’# + ?’等字符显然是分类的,可以先输入一个字符,然后判断后分别处理。还有map关联两个字符串就可以了,不用再进行编号-字符的转换,并查集时一定要注意祖先的初始化。
#include<iostream>
#include<cstdio>
#include<map>
#include<cstring>
using namespace std;
map<string,string>f;
string s,s1;
int t;
char ch;
string find(string x){
return f[x]==x?x:f[x]=find(f[x]);
}
int main(){
cin>>ch;
while(ch!='$'){
cin>>s;
if (ch=='#'){
s1=s;//记录父亲
if (f[s]=="") f[s]=s;//自己是自己的父亲
}
else if (ch=='+')
f[s]=s1;//s的祖先是s1
else
cout<<s<<" "<<find(s)<<endl;
cin>>ch;
}
return 0;
}