#include<iostream>
#include<iomanip>
#include<math.h>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<vector>
#include<set>
#include<stack>
#include<map>
#define maxn 10000000
#define mod 23333
#define base 233
using namespace std;
struct{
int du;
string name;
}fam[maxn];
char p[10];
string fa, so;
int fc = 0, sc = 0;
inline int find(int x) {
if (fam[x].du == x)return x;
return fam[x].du = find(fam[x].du);
}
inline void ad(int f, int s) {
f = find(f);
s = find(s);
fam[s].du = f;
}
int get(string a) {
int sum = 0;
for (int i = 0; i <= 5; ++i) {
sum += (i + 1) * (a[i] - 'A');
}
return sum;
}
//inline int read() {
// int w = 1, q = 0;
// char ch = ' ';
// while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
// if (ch == '-') w = -1, ch = getchar();
// while (ch >= '0' && ch <= '9') q = q * 10 + ch - '0', ch = getchar();
// return w * q;
//}
int main() {
for (int i = 1; i <= 100000; ++i) {
fam[i].du = i;
}
do {
cin >> p;
string ps = p;
if (p[0] == '#') {
fa =ps.substr(1,6);
if (fc == 0) {
fc = 1;
}
else if(fc==1){
sc = 0;
}
}
else if(p[0]=='+'){
so = ps.substr(1, 6);
sc = 1;
}
if (fc && sc) {
fam[get(fa)].name = fa;
fam[get(so)].name = so;
ad(fam[get(fa)].du, fam[get(so)].du);
}
if (p[0] == '?') {
string pp = ps.substr(1, 6);
cout << pp << " " << fam[find(get(pp))].name << endl;
}
} while (p[0] != '$');
return 0;
}