/* SI 335 Spring 2012
 * Project 2: OMA Service Selection
 *
 * This contains the "simple" algorithm to do the service
 * selection, provided as example/starter code.
 */

#include <iostream>
#include <string>

using namespace std;

struct Prole {
  string name;
  int* ranks;
  bool taken;
};

int main() {
  int k, n;

  // Read in the number of communities
  cin >> k;

  // Read in the community names
  string* comms = new string[k];
  for (int i=0; i<k; ++i)
    cin >> comms[i];

  // Read in the number of proles
  cin >> n;
  
  // Read in the proles' names and rankings
  Prole* proles = new Prole[n];
  for (int i=0; i<n; ++i) {
    cin >> proles[i].name;

    // Read in the rankings
    proles[i].ranks = new int[k];
    for (int j=0; j<k; ++j)
      cin >> proles[i].ranks[j];

    proles[i].taken = false;
  }

  // Now do the actual selection
  for (int i = 0; i < n; ++i) {
    int comm = i % k; // Which community gets this pick
    int nextPick;
    int rank = 1; // start with the top-ranked pick

    do {
      nextPick = 0;
      // Find the Prole with the given rank by this community
      while (proles[nextPick].ranks[comm] != rank)
        ++nextPick;
      ++rank;
    } while (proles[nextPick].taken); // If already taken, try next rank

    // Now we have the actual pick, so print it
    cout << proles[nextPick].name << ' ' << comms[comm] << endl;
    // And mark it as "taken"
    proles[nextPick].taken = true;
  }

  // De-allocate the dynamic memory we got
  for (int i=0; i<n; ++i) delete [] proles[i].ranks;
  delete [] proles;
  delete [] comms;
}
