哈利波特在魔法学校的必修课之一就是学习魔咒。据说魔法世界有100000种不同的魔咒,哈利很难全部记住,但是为了对抗强敌,他必须在危急时刻能够调用任何一个需要的魔咒,所以他需要你的帮助。
给你一部魔咒词典。当哈利听到一个魔咒时,你的程序必须告诉他那个魔咒的功能;当哈利需要某个功能但不知道该用什么魔咒时,你的程序要替他找到相应的魔咒。如果他要的魔咒不在词典中,就输出“what?”
给你一部魔咒词典。当哈利听到一个魔咒时,你的程序必须告诉他那个魔咒的功能;当哈利需要某个功能但不知道该用什么魔咒时,你的程序要替他找到相应的魔咒。如果他要的魔咒不在词典中,就输出“what?”
Input首先列出词典中不超过100000条不同的魔咒词条,每条格式为:
[魔咒] 对应功能
其中“魔咒”和“对应功能”分别为长度不超过20和80的字符串,字符串中保证不包含字符“[”和“]”,且“]”和后面的字符串之间有且仅有一个空格。词典最后一行以“@END@”结束,这一行不属于词典中的词条。
词典之后的一行包含正整数N(<=1000),随后是N个测试用例。每个测试用例占一行,或者给出“[魔咒]”,或者给出“对应功能”。Output每个测试用例的输出占一行,输出魔咒对应的功能,或者功能对应的魔咒。如果魔咒不在词典中,就输出“what?”Sample Input
[expelliarmus] the disarming charm [rictusempra] send a jet of silver light to hit the enemy [tarantallegra] control the movement of one's legs [serpensortia] shoot a snake out of the end of one's wand [lumos] light the wand [obliviate] the memory charm [expecto patronum] send a Patronus to the dementors [accio] the summoning charm @END@ 4 [lumos] the summoning charm [arha] take me to the sky
Sample Output
light the wand accio what? what?
第一眼看这题 就感觉用map暴力应该OK
结果爆内存了
还是老老实实用hash吧
hash其实就是把字符串映射为一个特有的数字然后通过查询这个特有的数字进行字符串查找
这题还让我学会了如何对结构体使用lower——bound 这题收获还是比较多的
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <string> 7 8 using namespace std; 9 const int maxn = 1e5 + 10; 10 char a[maxn][25], b[maxn][85]; 11 int num = 0; 12 struct node { 13 int Hash; 14 int id; 15 } key[maxn], tail[maxn] ; 16 int cmp(node a, node b) { 17 return a.Hash < b.Hash; 18 } 19 int bkdrhash(char *str) { 20 int seed = 131; 21 int ret = 0; 22 while(*str) 23 ret = ret * seed + (*str++); 24 return ret & 0x7fffffff; 25 } 26 void init() { 27 for (int i = 0 ; i < num ; i++) { 28 key[i].Hash = bkdrhash(a[i]); 29 key[i].id = i; 30 tail[i].Hash = bkdrhash(b[i]); 31 tail[i].id = i; 32 } 33 sort(key, key + num, cmp); 34 sort(tail, tail + num, cmp); 35 } 36 37 int main() { 38 while(scanf("%s", a[num])) { 39 if (a[num][0] == '@') break; 40 getchar(); 41 gets(b[num++]); 42 } 43 init(); 44 int n; 45 scanf("%d", &n); 46 getchar(); 47 for (int i = 0 ; i < n ; i++ ) { 48 node temp; 49 char str[120]; 50 gets(str); 51 if (str[0] == '[') { 52 temp.Hash = bkdrhash(str); 53 int mid = lower_bound(key, key + num, temp, cmp) - key; 54 if (key[mid].Hash == temp.Hash) printf("%s ", b[key[mid].id]); 55 else printf("what? "); 56 } else { 57 temp.Hash = bkdrhash(str); 58 int mid = lower_bound(tail, tail + num, temp, cmp) - tail; 59 if (tail[mid].Hash == temp.Hash) { 60 int len = strlen(a[tail[mid].id]); 61 a[tail[mid].id][len - 1] = 0; 62 printf("%s ", a[tail[mid].id] + 1); 63 } else printf("what? "); 64 } 65 } 66 return 0; 67 }