#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<cstring>
#include<string>
using namespace std;
int s[5035] = { 0 };
const int n = 5001;
void init() {
for (int i = 0; i <= n; i++) {
s[i] = i;
}
}
int find_set(int x) {
if (s[x] != x) {
s[x] = find_set(s[x]);
}
return s[x];
}
void merge_set(int x, int y) {
x = find_set(x);
y = find_set(y);
if (x != y) {
s[x] = s[y];
}
}
int main() {
init();
char as;
vector<string>na(1);
int pos = 0 , fa = 0;
while ((as = getchar()) != '$') {
if (as == '#' || as == '+') {
string tm;
cin >> tm;
int fl = 0;
for (int i = 0; i < na.size(); i++) {
if (tm == na[i]) {
pos = i; fl = 1; break;
}
}
if (fl == 0) {
pos = na.size();
na.push_back(tm);
}
if (as == '#')fa = pos;
else {
merge_set(pos, fa);
}
}
else if (as == '?') {
string p;
cin >> p;
cout << p << " ";
for (int i = 1; i <= pos; i++) {
if (na[i] == p) {
cout << na[s[i]] << '\n';
}
}
}
else {
break;
}
getchar();
}
return 0;
}