#include <string>       // std::string
#include <iostream>     // std::cout
#include <sstream> 
#include <climits>
#include <map>
#include <vector>
#include <queue>

using namespace std;

int n;
int m;
int t;

string GetFullName(vector<string> persons, string name)
{
  for(int i=0; i<persons.size(); i++)
  {
    size_t found = persons[i].find(name);
    if (found != std::string::npos)
    {
      // last name
      if (found + name.length() == persons[i].length())
      {
        return persons[i];
      }
      // first name
      if (persons[i][found + name.length()] == ' ')
      {
        return persons[i];
      }
    }
  }
}

int main()
{
    string tmp;
    getline(cin, tmp);
    stringstream ss(tmp);
    ss >> n; ss >> m;
  
  // get persons
  vector<string> persons;
  string s;
  for(int i=0; i<m; i++)
  {
    getline(cin, s);
    persons.push_back(s);
  }

  getline(cin, tmp);
  stringstream sss(tmp);
  sss >> t;

  map<int, queue<string> > counters;

  vector<int> status;
  for(int i=0; i<=n; i++) 
  { 
    status.push_back(0); 
    //queue<string> qs;
    //counters.insert(make_pair(i, qs));
  }
  for(int k=0; k<t; k++)
  {
    getline(cin, tmp);
    stringstream ops(tmp);
    int id = 0;
    int x = 0;
    ops >> id;
    if (id >=1 && id <= 4)
    {
      // read another int
      ops >> x;
      if (id == 1)
      {
        // change status : open/close
        if (status[x] == 1) status[x]=0;
          else status[x]=1;
      }
      else if (id == 2)
      {
        // read myName
        string name;
        ops >> name;
        string fullName = GetFullName(persons, name);
        if (status[x] == 1)
        {
          counters[x].push(fullName);
        }
      }
      else if (id == 3)
      {
          counters[x].pop();
      }
      else if (id == 4)
      {
        // print queue
        if (counters[x].size() == 0)
        {
          cout << "-1" << endl;
        }
        else
        {
          // print queue content, last -> first
          queue<string> tmpq(counters[x]);
          vector<string> array;
          while(!tmpq.empty())
          {
            array.push_back(tmpq.front());
            tmpq.pop();
          }
          for(int ai=array.size()-1; ai>=0; ai--)
          {
            if (ai != array.size()-1) cout << " ";
            cout << array[ai];
          }
          cout << endl;
        }
      }
    }
    else
    {
      // case 5
      // read myName
      string name;
      ops >> name;
      string fullName = GetFullName(persons, name);
      for(int i=1; i<=n; i++)
      {
        int found = 0;

        // check in queue i
        queue<string> tmpq(counters[i]);
        int firstRun = 0;
        while(!tmpq.empty())
        {
          if(tmpq.front()==fullName) { found = 1; break; }
          tmpq.pop();
        }      

        if (found) cout << i;  
      }
      cout << endl;
    }
  }

  return 0;
}