#include <utility>
#include <string>
#include <cassert>
#include <sstream>
#include <iterator>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <regex>
#include "validate.h"

using namespace std;
#define rep(i,n) for(int i=0;i<(n);i++)

void shop() {
    // Read problem input, create a map item -> category_rank
    int n, k;
    judge_in >> n >> k;
    
    unordered_multiset<string> items;
    rep(i, n) {
        string s;
        judge_in >> s;
        items.insert(s);
    }

    vector<string> order(k);
    rep(i, k) judge_in >> order[i];
    
    unordered_map<string, int> position;
    rep(i, k) position[order[i]] = i;

    unordered_map<string, string> category_of_item;
    rep(i, k) {
        string cat;
        int m;
        judge_in >> cat >> m;
        rep(j, m) {
            string item;
            judge_in >> item;
            category_of_item[item] = cat;
        }
    }

    // Validating answer
    int prev_rank = -1;
    string prev_answer = "---";
    string prev_category = "---";
    auto regex_is_az = regex("^[a-zA-Z]*$");
    rep(i, n) {
        string user_answer;
        if (!(author_out >> user_answer)) {
            wrong_answer("Failed to read %d'th move\n", i);
        }
        if (!regex_match(user_answer, regex_is_az)) {
            wrong_answer("Read a string which did not match [A-Za-z]*");
        }

        const auto el = items.find(user_answer);
        if (el == items.end()) {
            wrong_answer("The %d'th item provided by the user (%s) was not a bought item\n", i, user_answer.c_str());
        }
        items.erase(el);

        if (category_of_item.count(user_answer) <= 0) {
            wrong_answer("Could not find category for the %d'th item (%s)\n", i, user_answer.c_str());
        }

        string category = category_of_item[user_answer];
        int rank = position[category];
        if (rank < prev_rank) {
            wrong_answer("The %d'th item (%s in category %s) provided by the user should be sorted before the %d'th item (%s in category %s)\n", i, user_answer.c_str(), category.c_str(), i-1, prev_answer.c_str(), prev_category.c_str());
        }
        prev_rank = rank;
        prev_answer = user_answer;
        prev_category = category;
    }
}

int main(int argc, char **argv) {
    init_io(argc, argv);

    shop();

    /* Yay! */
    accept();
}
