并查集模板题,看大佬们都用字符哈希,像我这种不会哈希的蒟蒻只能用map了
#include<iostream>
#include<cmath>
#include<cstdio>
#include<map>
#include<string>
using namespace std;
map<string,string>f;
string find(string x)
{
return f[x]==x?x:f[x]=find(f[x]);//查找x的祖先
}
char ch;
string s,x;
int main()
{
for(int i=1;i;i++)
{
cin>>ch;
if(ch=='$') break;
if(ch=='#')
{
cin>>x;
if(f[x]=="") f[x]=x;//x还没有祖先,将x的祖先设为自己
}
else if(ch=='+')
{
cin>>s;
f[s]=x;//将s的祖先设为x,那么x的祖先也是s的祖先了
}
else if(ch=='?')
{
cin>>s;
cout<<s<<' '<<find(s)<<endl;//输出s的祖先是谁
}
}
return 0;
}