//Verdict: Runtime Error
#include<bits/stdc++.h>
using namespace std;
struct node{
int cnt_trees;
bool endmark;
node *next[128];
node(){
endmark=false;
cnt_trees=0;
for(int i=0;i<128;i++) next[i]=NULL;
}
}*root;
void insert_into_Trie(string str){
node *cur=root;
for(int i=0;str[i];i++){
int id=str[i];
if(cur->next[id]==NULL)
cur->next[id]=new node();
cur=cur->next[id];
}
cur->cnt_trees++;
}
int search_into_Trie(string str){
node *cur=root;
for(int i=0;str[i];i++){
int id=str[i];
cur=cur->next[id];
}
return cur->cnt_trees;
}
void del(node* cur)
{
for(int i= 0;i<128;i++)
if (cur->next[i])
del(cur->next[i]);
delete(cur);
}
int main()
{
int tc,n,q,cs=0;
string str;
cin>>tc;
while(tc--){
root=new node;
cin>>n;
while(n--){
cin>>str;
if(str.length()>3)
sort(str.begin()+1,str.end()-1);
insert_into_Trie(str);
}
cin>>q;
cout<<"Case "<<++cs<<":"<<endl;
getchar();
while(q--){
getline(cin,str);
int ans=1;
string temp="";
for(int i=0;str[i];++i){
if(str[i]==' '){
if(temp.length()>3)
sort(temp.begin()+1,temp.end()-1);
//cout<<temp<<endl;
ans*=search_into_Trie(temp);
temp="";
}
else temp+=str[i];
}
if(temp.length()>3)
sort(temp.begin()+1,temp.end()-1);
//cout<<temp<<endl;
ans*=search_into_Trie(temp);
cout<<ans<<endl;
}
del(root);
}
return 0;
}
Ly9WZXJkaWN0OiBSdW50aW1lIEVycm9yCgojaW5jbHVkZTxiaXRzL3N0ZGMrKy5oPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwpzdHJ1Y3Qgbm9kZXsKICAgIGludCBjbnRfdHJlZXM7CiAgICBib29sIGVuZG1hcms7CiAgICBub2RlICpuZXh0WzEyOF07CiAgICBub2RlKCl7CiAgICAgICAgZW5kbWFyaz1mYWxzZTsKICAgICAgICBjbnRfdHJlZXM9MDsKICAgICAgICBmb3IoaW50IGk9MDtpPDEyODtpKyspIG5leHRbaV09TlVMTDsKICAgIH0KfSpyb290OwoK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BnZXRjaGFyKCk7CiAgICB3aGlsZShxLS0pewogICAgICAgIGdldGxpbmUoY2luLHN0cik7CiAgICAgICAgaW50IGFucz0xOwogICAgICAgIHN0cmluZyB0ZW1wPSIiOwogICAgICAgIGZvcihpbnQgaT0wO3N0cltpXTsrK2kpewogICAgICAgICAgICBpZihzdHJbaV09PScgJyl7CiAgICAgICAgICAgICAgICBpZih0ZW1wLmxlbmd0aCgpPjMpCiAgICAgICAgICAgICAgICBzb3J0KHRlbXAuYmVnaW4oKSsxLHRlbXAuZW5kKCktMSk7CiAgICAgICAgICAgICAgICAvL2NvdXQ8PHRlbXA8PGVuZGw7CiAgICAgICAgICAgICAgICBhbnMqPXNlYXJjaF9pbnRvX1RyaWUodGVtcCk7CiAgICAgICAgICAgICAgICB0ZW1wPSIiOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGVsc2UgdGVtcCs9c3RyW2ldOwogICAgICAgIH0KICAgICAgICBpZih0ZW1wLmxlbmd0aCgpPjMpCiAgICAgICAgc29ydCh0ZW1wLmJlZ2luKCkrMSx0ZW1wLmVuZCgpLTEpOwogICAgICAgIC8vY291dDw8dGVtcDw8ZW5kbDsKICAgICAgICBhbnMqPXNlYXJjaF9pbnRvX1RyaWUodGVtcCk7CiAgICAgICAgY291dDw8YW5zPDxlbmRsOwogICAgfQogICAgZGVsKHJvb3QpOwogICAgfQogICAgcmV0dXJuIDA7Cn0K