本文主要是介绍字符串Hash 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?
思路:
通过哈希算法我们可以将字符串转化为一串数字,用于快速比较。
计算哈希值的算法举例:
我们通过确定seed和mod的值,可以通过这种计算方式获取每一个字符串对应的哈希值。
对于这道题,[魔咒] 功能,将魔咒和功能字符串首先加入到两个字符串数组中,获取他们在数组中的位置都为index,接着我们分别求出魔咒和功能的字符串对应的两个哈希值hashCur和hashFunc,然后设立两个map,用于对应字符串的哈希值和字符串在数组中的位置index。这样我们对于魔咒,就可以通过map找到他是否在魔咒数组中,并且在数组中的哪个位置,对应的功能也在功能数组的对应位置;对于功能找魔咒也是一样。
代码:
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<iostream>
#include<string>
#include<string.h>
#include<map>
#include<vector>
using namespace std;
const long long seed = 7;unsigned long long getHash(string& x)
{unsigned long long ans = 0, tem = seed;int size = x.size();for (int i = size - 1; i >= 0; i--){ans += tem * x[i];tem = tem * seed;}return ans;
}string curse[100005];
string function[100005];map<unsigned long long, int>mpCurse;
map<unsigned long long, int>mpFunc;int main()
{string temp;int tot = 0;while (getline(cin, temp)){if (temp == "@END@")break;string cur = "", fun = "";int i = 1;for (i; i < temp.size(); i++){if (temp[i] == ']')break;cur += temp[i];}i++;i++;for (i; i < temp.size(); i++){fun += temp[i];}curse[tot] = cur;function[tot] = fun;mpCurse[getHash(cur)] = tot;mpFunc[getHash(fun)] = tot;tot++;}int n;cin >> n;getchar();for (int i = 0; i < n; i++){getline(cin, temp);if (temp[0] != '['){unsigned long long hash = getHash(temp);if (mpFunc.find(hash) == mpFunc.end())cout << "what?" << endl;else cout << curse[mpFunc[hash]] << endl;}else{string str = "";for (int p = 1; p < temp.size() - 1; p++)str += temp[p];unsigned long long hash = getHash(str);if (mpCurse.find(hash) == mpCurse.end())cout << "what?" << endl;else cout << function[mpCurse[hash]] << endl;}}}
这篇关于字符串Hash ZJM 与霍格沃兹的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!