A - ZJM 与霍格沃兹
ZJM 为了准备霍格沃兹的期末考试,决心背魔咒词典,一举拿下咒语翻译题 。题库格式:[魔咒] 对应功能
背完题库后,ZJM 开始刷题,现共有 N 道题,每道题给出一个字符串,可能是 [魔咒],也可能是对应功能
ZJM 需要识别这个题目给出的是 [魔咒] 还是对应功能,并写出转换的结果,如果在魔咒词典里找不到,输出 “what?”Input
首先列出魔咒词典中不超过100000条不同的咒语,每条格式为: [魔咒] 对应功能
其中“魔咒”和“对应功能”分别为长度不超过20和80的字符串,字符串中保证不包含字符“[”和“]”,且“]”和后面的字符串之间有且仅有一个空格。魔咒词典最后一行以“@END@”结束,这一行不属于词典中的词条。
词典之后的一行包含正整数N(<=1000),随后是N个测试用例。每个测试用例占一行,或者给出“[魔咒]”,或者给出“对应功能”。Output
每个测试用例的输出占一行,输出魔咒对应的功能,或者功能对应的魔咒。如果在词典中查不到,就输出“what?”
思路:
- 如果直接使用
map<string, string>
会MLE
。 - 如果使用哈希:
- 首先存储所有的字符串,包括魔咒和对应功能;字符串在数组中的下标与其哈希值对应,即
map[hash] = index s[index] = 字符串
;这样在查询时首先判断是魔咒还是对应功能,如果是前者那么直接去掉[]
,之后判断bkdr(str)是否存在于map当中,如果存在那么输出结果,否则输出“what?”。 - 考虑Bkdr 哈希函数的实现:
- seed直接使用ASCII码
- mod采用1e9+7
- 使用快速幂计算seed的幂
- 首先存储所有的字符串,包括魔咒和对应功能;字符串在数组中的下标与其哈希值对应,即
实现:
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<vector>
#include<cstring>
#include<cstdio>
#include<cstdlib>
using namespace std;
const int mod = 1e9+7;
int quick_pow(int a,int x)
{//计算a的x次方
int res = 1;
while(x)
{
if(x & 1)res = res * a % mod;
a = a * a % mod;
x >>= 1;
}
return res;
}
long long bkdr(string str)
{
long long value = 0;
int n = str.size();
for(int i=1;i<=n;++i)
value += int(str[n-i]) * quick_pow(131,i) % mod;
return value;
}
string s1,s2,s;
map<long long,int> mp;
vector<string> res;
int index=0;
long long tmp;
int main()
{
//ios::sync_with_stdio(false);
while(true)
{
getline(cin,s);
if(s == "@END@")break;
s1 = s.substr(1,s.find("] ")-1);
s2 = s.substr(s.find("] ")+2,s.length() - s.find("] ")-1);
res.push_back(s1);
mp[bkdr(s2)] = index++;
res.push_back(s2);
mp[bkdr(s1)] = index++;
}
int N;
cin >> N;
getchar();
while(N--)
{
getline(cin,s);
if(s.find("[")!= std::string::npos)
{
s.erase(0,1);
s.erase(s.size()-1,1);
}
tmp = bkdr(s);
if(mp.find(tmp) == mp.end())
cout<<"what?"<<endl;
else cout<<res[mp[tmp]]<<endl;
}
return 0;
}
BUG记录:
- 注意后面使用了
getchar()
但是前面已经关闭同步了,注释后正确。