题目描述
给出一系列二元组:[原字符串] 翻译字符串;
进行若干次查询,给出原字符串或翻译字符串,输出对应的翻译字符串或原字符串。
输入
首先给出若干行,每行一个二元组:[原字符串] 翻译字符串;
最后一行以"@END@"结尾;
之后一行给出一个整数q,表示询问次数;
之后q行,每行一个[原字符串]或翻译字符串;
输出
输出q行,每行输出对应字符串。
输入样例
[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
输出样例
light the wand
accio
what?
what?
基本思路
该题直接利用map建立字符串到字符串的映射会导致MLE,因此,应当使用hash函数建立字符串到整数的映射,将所有的字符串存入一个数组,再利用map建立hash(字符串)到对应字符串的数组索引的映射。
hash函数的实现如下:
long long _hash(string &st)
{
long long v=0;
for(int i=0, l=st.length();i<l;i++)
{
v = (v + (long long)(st[i])*seed) %mod;
v = v*seed % mod;
}
return v;
}
需要注意的点
- hash值可能会比较大,所以最好使用longlong存储;
- 为了防止hash值过大导致溢出,应该边计算hash边取模;
- seed相当于计算hash的一个参数,不宜取的太小,并且要是质数。
完整代码
#include<iostream>
#define seed 131
#define mod 1000000007
#include<string>
#include<map>
#include<vector>
using namespace std;
vector<string> s;
int idx;
map<long long, int> mp;
long long _hash(string &st)
{
long long v=0;
for(int i=0, l=st.length();i<l;i++)
{
v = (v + (long long)(st[i])*seed) %mod;
v = v*seed % mod;
}
return v;
}
int main ()
{
string k, v, line;
while(true)
{
getline(cin, line);
if(line == "@END@") break;
k = line.substr(0, line.find("] ")+1);
v = line.substr(line.find("] ")+2, line.length() - line.find("] ") - 1);
s.push_back(v);mp.insert({_hash(k), idx++});
s.push_back(k);mp.insert({_hash(v), idx++});
}
int n;
cin>>n;
getchar();
string q;
string res;
for(int i=0;i<n;i++)
{
getline(cin, q);
if(mp.find(_hash(q)) == mp.end()) cout<<"what?"<<endl;
else
{
res = s[mp[_hash(q)]];
if(res[0] == '[') res = res.substr(1, res.length() - 2);
cout<<res<<endl;
}
}
return 0;
}