1 #include <cstdio>
2 #include <cmath>
3 #include <algorithm>
4 #include <iostream>
5 #include <cstring>
6 #include <queue>
7 #include <vector>
8 #include <bitset>
9 #include <map>
10 #include <string>
11 #define maxn 1050
12 #define maxk 9000
13 using namespace std;
14
15 int n,k;
16 long long int size[maxn];
17 bitset<maxn> mask; //用来记录最后出现搜索的tags的编号;
18 map <string,bitset<maxn> > mmap;
19 map <string,bitset<maxn> >::iterator iter;
20
21 int main()
22 {
23 // if(freopen("input.txt","r",stdin)== NULL) {printf("Error\n"); exit(0);}
24 while(cin>>n){
25 mmap.clear();
26 char str[maxn];
27 for(int i=1;i<=n;i++){
28 scanf("%s %lld",str,&size[i]);
29 char *p,*q;
30 p = str;
31 while((p = strchr(p,'[')) != NULL){
32 q = strchr(p,']');
33 string temp = string(p+1,q);
34 mmap[temp].set(i);
35 p = q;
36 }
37 }
38 cin>>k;
39 for(int i=1;i<=k;i++){
40 scanf("%s",str);
41 char *p,*q;
42 p = str;
43 mask.set();
44 while((p = strchr(p,'[')) != NULL){ //***
45 q = strchr(p,']');
46 string temp = string(p+1,q);
47 iter = mmap.find(temp);
48 if(iter == mmap.end()){
49 mask.reset();
50 break; //*****
51 }
52 else mask &= iter->second;
53 p = q;
54 }
55 long long int ans = 0;
56 for(int i=1;i<=n;i++){
57 if(mask[i]) ans += size[i];
58 }
59 printf("%lld\n",ans);
60 }
61 }
62 return 0;
63 }