#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <algorithm>
using namespace std;

int cSize, sortOrder;

struct Cake{
  string name;
  int key;
  unsigned int size;
  Cake():name(""),size(0),key(0){}
  Cake(string n, unsigned int s):name(n),size(s),key(-1){}
  bool operator< (const Cake & c) const{
    if (key == c.key){
      if (sortOrder) return size > c.size;
      else return size < c.size;
    }
    else return (key < c.key);
  }
};

map<string, int> msi;
Cake cakes[100];

int main(){
  int cCnt; cin >> cCnt;
  unsigned int x, t1;
  string str;
  bool nf(false), hasOutput;
  while (cCnt--){
    if (nf) cout << endl;
    nf = true;
    
    msi.clear();
    
    // Style
    cin >> cSize; getline(cin, str);
    for (int i=0 ; i<cSize ; ++i){
      getline(cin, str);
      t1 = str.rfind(' ');
      istringstream iss(str.substr(t1, str.length()-t1));
      str = str.substr(0, t1);
      iss >> t1;
      //cerr << t1 << '\t' << "\"" << str << "\"" << endl;
      cakes[i].name = str;
      cakes[i].size = t1;
      cakes[i].key = -1;
      msi[str] = -1;
    }
    
    // Preference
    cin >> x; getline(cin, str);
    for (int i=0 ; i<x ; ++i){
      getline(cin, str);
      msi[str] = i;
    }
    cin >> sortOrder;
    
    // Style Map
    hasOutput = false;
    for (int i=0 ; i<cSize ; ++i){
      cakes[i].key = msi[cakes[i].name];
      if (cakes[i].key >= 0) hasOutput = true;
    }
      
    // Sort
    sort(cakes, cakes+cSize);
    
    // Output
    if (hasOutput){
      for (int i=0 ; i<cSize ; ++i){
        if (cakes[i].key >= 0)
          cout << cakes[i].name << " " << cakes[i].size << endl;
      }
    }
    else {
      cout << "Do you know what does a piece of cake mean?" << endl;
    }
  }

  return 0;
}
