魔咒词典

题意:输入魔咒输出功能,输入功能找到魔咒,否则输出"what?"

思路:直接用map<string>会超内存,于是想到用字符串hash解决内存问题

代码:

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #define N 100005
 5 using namespace std;
 6 char func[N][85];//功能
 7 char magic[N][25];//咒语
 8 int num=1;
 9 struct node//Hash值对应的数组下标
10 {
11     int Hash;
12     int l;
13 } key[N],tail[N];//咒语和功能
14 int cmp(node a,node b)//比较函数
15 {
16     return a.Hash<b.Hash;
17 }
18 
19 unsigned int BKDRHash(char *str)//Hash算法
20 {
21     unsigned int seed = 131;
22     unsigned int hash = 0;
23 
24     while (*str)
25     {
26         hash = hash * seed + (*str++);
27     }
28     return (hash & 0x7FFFFFFF);
29 }
30 void init()//初始化,计算所有串的Hash值
31 {
32     for(int i=1; i<num; i++)
33     {
34         key[i].Hash=BKDRHash(magic[i]);
35         key[i].l=i;
36         tail[i].Hash=BKDRHash(func[i]);
37         tail[i].l=i;
38     }
39     sort(key,key+num,cmp);//按照Hash值排序,方便二分查找
40     sort(tail,tail+num,cmp);
41 }
42 int main()
43 {
44 
45     while(scanf("%s",magic[num]))
46     {
47         if(!strcmp(magic[num],"@END@"))
48             break;
49         getchar();
50         gets(func[num++]);
51     }
52     init();
53     int n;
54     scanf("%d",&n);
55     getchar();
56     while(n--)
57     {
58         node tmp;
59         char str[120];
60         gets(str);
61         if(str[0]=='[')//是咒语
62         {
63             tmp.Hash=BKDRHash(str);
64             int mid=lower_bound(key,key+num,tmp,cmp)-key;
65             if(key[mid].Hash!=tmp.Hash)
66                 printf("what?\n");
67             else
68                 printf("%s\n",func[key[mid].l]);
69         }
70         else
71         {
72             tmp.Hash=BKDRHash(str);
73             int mid=lower_bound(tail,tail+num,tmp,cmp)-tail;
74             if(tail[mid].Hash!=tmp.Hash)
75                 printf("what?\n");
76             else
77             {
78                 int l=strlen(magic[tail[mid].l]);
79                 magic[tail[mid].l][l-1]=0;
80                 printf("%s\n",magic[tail[mid].l]+1);
81             }
82         }
83     }
84     return 0;
85 }

 

posted @ 2020-03-15 13:47  Sunboy482  阅读(84)  评论(0)    收藏  举报