#include<algorithm>
#include<set>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<iostream>
#include<set>
#include<vector>
#include<queue>
#include<cmath>
#include<cstdio>
#include<map>
#include<stack>
#include<string>
using namespace std;
#define sfi(i) scanf("%d",&i)
#define pri(i) printf("%d\n",i)
#define sff(i) scanf("%lf",&i)
#define ll long long
#define mem(x,y) memset(x,y,sizeof(x))
#define INF 0x3f3f3f3f
#define eps 1e-6
#define PI acos(-1)
#define lowbit(x) ((x)&(-x))
#define zero(x) (((x)>0?(x):-(x))<eps)
#define fl() printf("flag\n")
#define MOD(x) ((x%mod)+mod)%mod
#define FASTIO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
ll gcd(ll a,ll b){while(b^=a^=b^=a%=b);return a;}
const int maxn=2e5+9;
const int mod=1e9+7;
template <class T>
inline void sc(T &ret)
{
char c;
ret = 0;
while ((c = getchar()) < '0' || c > '9');
while (c >= '0' && c <= '9')
{
ret = ret * 10 + (c - '0'), c = getchar();
}
}
struct node
{
char c;
int num;
node *le,*ri;
node()
{
c='#';
num=0;
le=NULL;
ri=NULL;
}
bool operator < (const node &b)const
{
return num>b.num;
}
};
priority_queue<node>q;
node* build()
{
while(q.size()>1)
{
node t1=q.top();
q.pop();
node t2=q.top();
q.pop();
//cout<<t1.num<<" "<<t2.num<<endl;
node *tp1=new node;
tp1->c=t1.c;
tp1->num=t1.num;
tp1->le=t1.le;
tp1->ri=t1.ri;
node *tp2=new node;
tp2->c=t2.c;
tp2->num=t2.num;
tp2->le=t2.le;
tp2->ri=t2.ri;
node *tmp=new node;
tmp->c='#';
tmp->num=tp1->num+tp2->num;
tmp->le=tp1;
tmp->ri=tp2;
node tt;
tt.c=tmp->c;
tt.num=tmp->num;
tt.le=tmp->le;
tt.ri=tmp->ri;
q.push(tt);
}
node rt;
node *root=new node;
rt=q.top();
q.pop();
root->c=rt.c;
root->num=rt.num;
root->le=rt.le;
root->ri=rt.ri;
return root;
}
bool mp[maxn];
int id;
bool f=0;
void Set(node * rt,int cnt)
{
if(!rt) return ;
if(rt->c!='#')
{
cout<<rt->c<<":";
for(int i=0;i<cnt;i++)
{
cout<<mp[i];
}
cout<<endl;
}
mp[cnt]=0;
Set(rt->le,cnt+1);
mp[cnt]=1;
Set(rt->ri,cnt+1);
}
void Coding(node *rt,char c,int cnt)
{
if(!rt) return ;
if(rt->c==c)
{
for(int i=0;i<cnt;i++)
{
cout<<mp[i];
}
}
mp[cnt]=0;
Coding(rt->le,c,cnt+1);
mp[cnt]=1;
Coding(rt->ri,c,cnt+1);
}
void Mask(node *rt,string s,int cnt)
{
if(!rt) return ;
if(f) return ;
if(rt->c!='#')
{
cout<<rt->c;
id=cnt;
f=1;
return ;
}
if(s[cnt]-'0'==1)
{
Mask(rt->ri,s,cnt+1);
}
else if(s[cnt]-'0'==0)
{
Mask(rt->le,s,cnt+1);
}
}
int main()
{
int n;
cin>>n;//n个码
for(int i=0;i<n;i++)
{
node tmp;
cin>>tmp.c>>tmp.num;
q.push(tmp);
}
node *root=build();//建树
Set(root,0);
int op=1;
while(cin>>op)//1掩码,2译码,0退出
{
if(op==0) break;
if(op==1)
{
string s;
cin>>s;
int len=s.length();
for(int i=0;i<len;i++)
{
Coding(root,s[i],0);
}
cout<<endl;
}
else
{
string s;
cin>>s;
int len=s.length();
id=0;
while(id<len)
{
f=0;
Mask(root,s,id);
//cout<<id<<endl;
}
cout<<endl;
}
}
return 0;
}
//样例
/*
5
A 10
B 5
r 12
M 33
q 9
M:0
B:100
q:101
A:110
r:111
1
rrBBAq
111111100100110101
2
0100101111
MBqr
*/