并查集,裸题
本题要点:
1、 n <= 50000, 把名字离散化为整数,后面就是并查集的操作。压缩路径。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <string>
using namespace std;
const int MaxN = 5e4 + 10;
int fa[MaxN];
map<string, int> mp;
string s_int[MaxN];
int cnt;
int get(int x)
{
if(x == fa[x])
return x;
return fa[x] = get(fa[x]);
}
int main()
{
for(int i = 1; i < MaxN; ++i)
fa[i] = i;
string str, name, parent;
while(cin >> str)
{
if(str == "$") break;
name = str.substr(1, 6);
if(mp.find(name) == mp.end())
{
mp[name] = ++cnt;
s_int[cnt] = name;
}
if(str[0] == '#')
{
parent = name;
}else if(str[0] == '+'){
fa[mp[name]] = mp[parent];
}else{
cout << name << " " << s_int[get(mp[name])] << endl;
}
}
return 0;
}
/*
#George
+Rodney
#Arthur
+Gareth
+Walter
#Gareth
+Edward
?Edward
?Walter
?Rodney
?Arthur
$
*/
/*
Edward Arthur
Walter Arthur
Rodney George
Arthur Arthur
*/