正题
题目链接:
https://www.luogu.org/problemnew/show/P2814
大意
有n个父子关系(可能不止一个孩子),询问一些人最大的祖先
代码
#include<cstdio>
#include<map>
#include<string>
#include<iostream>
using namespace std;
map<string,string> father;//map库
string name,fathers;
char c;
string find(string x)
{
if (x!=father[x]) return father[x]=find(father[x]);
return father[x];
}
void unionn(string x,string y)
{
string fa=find(x),fb=find(y);
father[fa]=fb;
}
int main()
{
while (true)
{
cin>>c;
if (c=='$') break;
cin>>name;
if (father[name]=="") father[name]=name;
if (c=='#')
{
fathers=name;//记录父亲
}
if (c=='+')
{
unionn(name,fathers);//连接
}
if (c=='?')
{
cout<<name<<' '<<find(name)<<endl;//询问
}
}
}