Code
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
unordered_map<string, pair<string, int>> p;
string find(string x) {
if (x != p[x].first)
p[x].first = find(p[x].first);
return p[x].first;
}
void merge(string x, string y) {
string px = find(x), py = find(y);
if (px != py) {
if (p[px].second < p[py].second)
swap(px, py);
p[py].first = px;
p[px].second += p[py].second;
}
}
int main() {
char ch;
string s, s1;
cin >> ch;
while (ch != '$') {
cin >> s;
if (ch == '#') {
s1 = s;
if (p.find(s) == p.end())
p[s] = {s, 1};
else if (ch == '+')
merge(s, s1);
else
cout << s << ' ' << find(s) << endl;
cin >> ch;
}
}
}