#include <iostream> #include <cstring> #include <cstdio> #include <map> #include <string> using namespace std; struct TNode { int num; TNode * next[26]; TNode() { num=0; memset(next,0,sizeof(next)); } }; int count[10]={1,3,3,3,3,3,4,3,4}; char aset[10][4]={{'-'},{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}}; TNode * root =NULL; map<string,int>mq; void insert(char * s,int count) { int l = strlen(s); TNode * p = root; int i = 0; for(i=0;i<l;i++) { if(p->next[s[i]-'a']==NULL) { p->next[s[i]-'a'] = new TNode; p->next[s[i]-'a']->num = count; } else { p->next[s[i]-'a']->num+=count ; } p=p->next[s[i]-'a']; } } int find(char *s,int k) { int l = strlen(s); TNode * p =root; int i =0; for(i=0;i<l;i++) { if(p->next[s[i]-'a']==NULL) return 0; else { if(i==k-1) return p->next[s[i]-'a']->num; p = p->next[s[i]-'a']; } } return 0; } char buf[110]; char max_buf[110]; int max_f=0; bool check(char *s,int l) { string str(s,l+1); //cout<<str<<endl; map<string,int>::iterator it = mq.find(str); if(it == mq.end()) return true; if(it->second == 0) return false; else return true; } void dfs(char *s,int l,int k) { if(k == l+1) { int tmp = find(buf,k); string s(buf,k); //cout<<s<<endl; if(tmp!=0) { pair<string ,int>pa(s,1); mq.insert(pa); } else { pair<string,int>pa(s,0); mq.insert(pa); } if(tmp > max_f) { max_f = tmp; memset(max_buf,0,sizeof(max_buf)); memcpy(max_buf,buf,k); } return; } int i =0; for(i=0;i<count[s[k]-'1'];i++) { buf[k]=aset[s[k]-'1'][i]; if(check(buf,k)) dfs(s,l,k+1); } } void del(TNode * p) { int i = 0; for(i=0;i<26;i++) { if(p->next[i]) del(p->next[i]); } delete p; } int main() { int t; scanf("%d",&t); int c=1; while(c<=t) { root = new TNode; mq.clear(); printf("Scenario #%d:/n",c); int n,m; scanf("%d",&n); char word[110]; int k=0; memset(word,0,sizeof(word)); int i = 0; for(i=0;i<n;i++) { scanf("%s %d",word,&k); insert(word,k); } scanf("%d",&m); char dbuf[110]; memset(dbuf,0,sizeof(dbuf)); for(i=0;i<m;i++) { scanf("%s",dbuf); int l = strlen(dbuf); int j = 0; if(l==1) { } else { for(j=0;j<l-1;j++) { dfs(dbuf,j,0); if(max_f >0) { printf("%s/n",max_buf); } else { printf("MANUALLY/n"); } max_f=0; memset(buf,0,sizeof(buf)); } } printf("/n"); memset(dbuf,0,sizeof(dbuf)); } printf("/n"); c++; del(root); } }