以下代码是会WA的(直接套模板):
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
using namespace std;
#define endl '\n'
char op;
string x,y,z;
map<string,string>f;
string find(string x)
{
return x==f[x]?x:f[x]=find(f[x]);
}
void merge(string x,string y)
{
f[find(x)]=find(y);
return;
}
int main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
while(cin>>op)
{
if(op=='$') return 0;
if(op=='#')
{
cin>>x;
if(f.count(x)==0) f[x]=x;
}
if(op=='+')
{
cin>>y;
merge(y,x);
}
if(op=='?')
{
cin>>z;
cout<<z<<" "<<find(z)<<endl;
}
}
return 0;
}
但将模板中的merge函数改成如下:
void merge(string x,string y)
{
f[x]=y;
return;
}
就可以AC了,这是为什么呢?