A - ZJM 与霍格沃兹
题目描述
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?
解题思路
字符串哈希: 将字符串转为一串数字,用于快速比较
• 常用哈希算法 — Bkdr Hash 算法
举例
• Hash 值: 1∗𝑠𝑒𝑒𝑑! +5∗𝑠𝑒𝑒𝑑" +4∗𝑠𝑒𝑒𝑑#
• seed 常见取值为 7、17、131
• 𝑚𝑜𝑑 常见取值为 1𝑒9 + 7 或采用𝑢𝑛𝑠𝑖𝑔𝑛𝑒𝑑 𝑙𝑜𝑛𝑔 𝑙𝑜𝑛𝑔自然溢出
(1)魔咒词典的初始化:
利用一个string类型的数组dictionary存储所输入的“魔咒” 和 “对应功能”的字符串;
分别考虑 “魔咒” 和 “对应功能”,利用Hash算法将两段字符串转换成数字,作为map结构的第一元素,第二元素记录下这段字符在dictionary数组的下标位置;
(2)查询操作:
首先判断输入的字符串是属于 “魔咒” 和 “对应功能”中的哪一类,然后根据Hash算法获得对应的数字,并在map结构中查询出其在dictionary数组中的对应位置,最后进行输出即可;
解题代码
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
const int inf = 1e9;
vector<string> dictionary;
map <unsigned long long, int> m;
int count_number = 0;
unsigned long long Hash(string x) {
unsigned long long ans = 0;
for (int i = 0; i < x.length(); i++) {
ans = (ans + (unsigned long long)(x[i]) * 7) % inf;
ans = ans * 7 % inf;
}
return ans;
}
int main() {
string a, b, c;
//初始化字典
while (getline(cin, a)) {
if (a == "@END@") break;
b = a.substr(0, a.find("] ") + 1);
c = a.substr(a.find("] ") + 2, a.length() - a.find("] ") - 1);
dictionary.push_back(b);
dictionary.push_back(c);
m.insert({Hash(b), count_number++});
m.insert({Hash(c), count_number++});
}
//进行操作
int N; cin>>N;
string s;
getline(cin, s);
for (int x = 0; x < N; x++) {
getline(cin, s);
if (m.find(Hash(s)) != m.end()){
if(s[0] == '[') {
string ans = dictionary[m[Hash(s)] + 1];
cout<<ans<<endl;
}
else {
string ans = dictionary[m[Hash(s)] - 1];
cout<<ans.substr(1, ans.length() - 2)<<endl;
}
}
else
cout<<"what?"<<endl;
}
return 0;
}