#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <functional>
#include <cstring>
#include <map>
#include <climits>
using namespace std;
typedef struct BiTNode {
char key;
int weight;
BiTNode *lchild, *rchild;
BiTNode(char k = '\0', int w = 0, BiTNode* l = NULL, BiTNode* r = NULL) : key(k), weight(w), lchild(l), rchild(r) {}
} *BiTree;
struct cmp {
bool operator() (const BiTree& a, const BiTree& b)
{
return a->weight > b->weight;
}
};
priority_queue<BiTree, vector<BiTree>, cmp> q;
int N;
char key[64];
int frequence[CHAR_MAX + 5];
int depth[CHAR_MAX + 5];
bool flag = true;
BiTree BuildHaffmanTree()
{
BiTree T;
while (q.size() > 1)
{
T = new BiTNode();
T->lchild = q.top();
q.pop();
T->rchild = q.top();
q.pop();
T->weight = T->lchild->weight + T->rchild->weight;
q.push(T);
}
return T;
}
void setdepth(BiTree T, int d)
{
if (!T)
return;
depth[T->key] = d;
setdepth(T->lchild, d + 1);
setdepth(T->rchild, d + 1);
}
void destroyTree(BiTree T)
{
if (!T)
return;
destroyTree(T->lchild);
destroyTree(T->rchild);
delete T;
}
BiTree insert(BiTree& T, const char *path)
{
if (*path == '\0')
return NULL;
if (*path == '0')
{
}
}
int get_minicost(BiTree T)
{
int minicost = 0;
setdepth(T, 0);
for (int i = 0; i < N; ++i)
{
minicost += depth[key[i]] * frequence[key[i]];
}
return minicost;
}
int main(void)
{
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
BiTree Tree;
char code[64][64];
int n, w;
char k;
cin >> N;
for (int i = 0; i < N; ++i)
{
cin >> key[i] >> w;
frequence[key[i]] = w;
Tree = new BiTNode(key[i], w);
q.push(Tree);
}
Tree = BuildHaffmanTree();
int minicost = get_minicost(Tree);
destroyTree(Tree);
cin >> n;
while (n--)
{
flag = true;
BiTree root = new BiTNode();
int cur_cost = 0;
for (int i = 0; i < N; ++i)
{
cin >> key[i] >> code[i];
cur_cost += frequence[key[i]] * strlen(code[i]);
}
if (cur_cost != minicost)
flag = false;
else
{
for (int i = 0; i < N && flag; ++i)
{
BiTree *cur = &root; //这样才能改变root
int len = strlen(code[i]);
for (int j = 0; j < len; ++j)
{
if (code[i][j] == '0')
cur = &(*cur)->lchild;
else
cur = &(*cur)->rchild;
if (!*(cur))
*cur = new BiTNode();
else if (j + 1 < len)
continue;
else
{
flag = false;
break;
}
}
}
}
cout << (flag ? "Yes" : "No") << endl;
destroyTree(root);
}
return 0;
}