P2814 家谱
分析:
这题用hash和并查集也可以解,但hash实在太麻烦,会把人写死,由于本人最近在练习map,就不管并查集了。
f
a
[
1
]
=
2
fa[1]=2
fa[1]=2 意思是
1
1
1 的父亲是
2
2
2.
f
a
[
“
R
o
d
n
e
y
”
]
=
G
e
o
r
g
e
fa[“Rodney ”]=George
fa[“Rodney”]=George 同理
对于最后查询而言,假设查询
S
S
S的祖先,
s
t
r
i
n
g
string
string
s
s
=
s
ss=s
ss=s,如果ss出现在father数组中,
s
s
=
f
a
[
s
]
ss=fa[s]
ss=fa[s];如果没有出现,那么说明
s
s
ss
ss的父亲就是他自己,也就是
S
S
S的祖先。
Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<string,string> fa;
char c;
string f,s;
while(1)
{
cin>>c;
if(c=='$') break;
if(c=='#') cin>>f;
if(c=='+')
{
cin>>s;
fa[s]=f;
}
if(c=='?')
{
cin>>s;
cout<<s<<' ';
string ss=s;
while(fa.count(ss))
ss=fa[ss];
cout<<ss<<endl;
}
}
return 0;
}