#include <bits/stdc++.h>
using namespace std;
struct node
{
string s;
string c;
string room;
string date;
string num;
int score;
node(string s,string c,string a,string b,string d,int score):s(s),c(c),room(a),date(b),num(d),score(score){}
};
bool cmp(const node & a,const node & b)
{
if(a.score != b.score)
return a.score>b.score;
else
return a.s<b.s;
}
bool cmp1(const pair<string,int>p1, const pair<string,int>p2)
{
if(p1.second != p2.second)
return p1.second > p2.second;
else
return p1.first < p2.first;
}
int main() {
int N,M;
scanf("%d %d",&N,&M);
// cin>>N>>M;
string s;
int score;
vector<node>nodes;
for(int i = 0;i<N;i++)
{
cin>>s>>score;
nodes.push_back(node(s,s.substr(0,1),s.substr(1,3),s.substr(4,6),s.substr(10,3),score));
}
int k;
string t;
for(int i = 0;i<M;i++)
{
cin>>k>>t;
printf("Case %d: %d %s\n",i+1,k,t.c_str());
int flag = 0;
if(k == 1)
{
sort(nodes.begin(),nodes.end(),cmp);
for(int i = 0;i<nodes.size();i++)
{
if(nodes[i].c == t)
{
flag = 1;
printf("%s %d\n",nodes[i].s.c_str(),nodes[i].score);
//cout<<nodes[i].s<<" "<<nodes[i].score<<endl;
}
}
}
else if(k == 2)
{
int all_P = 0,all_score = 0;
for(int i = 0;i<nodes.size();i++)
{
if(nodes[i].room == t)
{
flag = 1;
all_P++;
all_score += nodes[i].score;
}
}
if(flag) printf("%d %d\n",all_P,all_score);
} else{
unordered_map<string,int>mp;
vector<pair<string,int>>v;
for(int i = 0;i<nodes.size();i++)
{
if(nodes[i].date == t)
{
mp[nodes[i].room]++;
}
}
for(auto it = mp.begin();it != mp.end();it++)
{
v.push_back(make_pair(it->first,it->second));
}
sort(v.begin(),v.end(),cmp1);
//print
for(int i = 0;i<v.size();i++)
{
flag = 1;
printf("%s %d\n",v[i].first.c_str(),v[i].second);
}
}
if(!flag) cout<<"NA"<<endl;
}
return 0;
}
/**
8 4
B123180908127 99
B102180908003 86
A112180318002 98
T107150310127 62
A107180908108 100
T123180908010 78
B112160918035 88
A107180908021 98
1 A
2 107
3 180908
2 999
**/