#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    multiset<string> st[20];
    int n; cin >> n;
    while(n--){
        int t; cin >> t;
        if(t==0){
            int n,m; cin >> n >> m;
            for(int i=0;i<m;i++){
                string s; cin >> s;
                st[n-1].insert(s);
            }
        }
        else if(t==1){
            string s; cin >> s;
            int res=-1;
            for(int i=0;i<20;i++){
                if(st[i].find(s)!=st[i].end()){
                    res=i+1;
                    auto it=st[i].lower_bound(s);
                    st[i].erase(it);
                    break;
                }
            }
            printf("%d\n",res);
        }
        else{
            int n; cin >> n;
            st[n-1].clear();
        }
    }
}