题目
ZJM 为了准备霍格沃兹的期末考试,决心背魔咒词典,一举拿下咒语翻译题
题库格式:[魔咒] 对应功能
背完题库后,ZJM 开始刷题,现共有 N 道题,每道题给出一个字符串,可能是 [魔咒],也可能是对应功能
ZJM 需要识别这个题目给出的是 [魔咒] 还是对应功能,并写出转换的结果,如果在魔咒词典里找不到,输出 “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?
解题思路
本题较麻烦的是需要严格按照要求进行字符串的处理,例如题目中提到“]”和后面的字符串之间有且仅有一个空格,如果多处理了一个空格就会WA。
Bkdr Hash 算法,字符串:𝑎𝑒𝑑 对应 Hash 值:(1∗𝑠𝑒𝑒𝑑^3 +5∗𝑠𝑒𝑒𝑑^2 +4∗𝑠𝑒𝑒𝑑^1 ) % 𝑚𝑜𝑑。seed 常见取值为 7、17、131。𝑚𝑜𝑑 常见取值为 1𝑒9+7 或采用𝑢𝑛𝑠𝑖𝑔𝑛𝑒𝑑 𝑙𝑜𝑛𝑔 𝑙𝑜𝑛𝑔自然溢出,用来快速查询一个串是否出现过。相应的数据存储到map中。
程序源码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<map>
#include<vector>
#include<string.h>
using namespace std;
unsigned long long calcHash(char* w) { //计算Hash
unsigned long long rs = 0;
unsigned long long base = 1;
int i = 0;
if (w[0] == '[') i = 1;
while (w[i] != '\0' && w[i] != ']') {
rs += w[i] * base;
base *= 7;
i++;
}
return rs;
}
int main() {
char* word;
char* info;
map<unsigned long long, char*> words;
map<unsigned long long, char*> infos;
char tmp[10];
while (1) {
word = new char[25];
info = new char[85];
scanf("%[\n\[@]", tmp);
scanf("%[^\]@]", word);
getchar();
if (strcmp(word, "END") == 0) break;
getchar();
scanf("%[^\n]", info);
words.insert(pair<unsigned long long, char*>(calcHash(info), word)); //插入map对
infos.insert(pair<unsigned long long, char*>(calcHash(word), info));
}
int n;
cin >> n;
info = new char[85];
for (int ii = 0; ii < n; ++ii) {
scanf("%[\n]", tmp);
scanf("%[^\n]", info);
if (info[0] == '[') { //input word
unsigned long long w = calcHash(info);
map<unsigned long long, char*>::iterator it = infos.find(w);
if (it == infos.end()) {
printf("what?\n");
}
else {
printf("%s\n", it->second);
}
}
else { //input info
unsigned long long w = calcHash(info);
map<unsigned long long, char*>::iterator it = words.find(w);
if (it == words.end()) {
printf("what?\n");
}
else {
printf("%s", it->second);
printf("\n");
};
}
}
}