前言
哈希函数,字符串哈希
#include <iostream>
#include <map>
#include <utility>
#include <vector>
#include <string>
using namespace std;
int base = 65537;
int mode = 1e9 + 7;
int myHash (string s) {
long long res = 0;
for (int i = 0; i < s.size(); i++)
res = (res * base + (s[i] - 'a')) % mode;
return res;
}
int main() {
map<int, int> hash2pos;
vector<string> dicts;
string str;
while (getline(cin, str) && str != "@END@") {
int pos = str.find("]");
string charms = str.substr(0, pos+1);
string func = str.substr(pos+2);
int charms_hash = myHash(charms);
int func_hash = myHash(func);
dicts.push_back(charms);
dicts.push_back(func);
hash2pos[charms_hash] = dicts.size() - 1;
hash2pos[func_hash] = dicts.size() - 2;
}
int N;
cin >> N;
getchar();
while (N--) {
getline(cin, str);
int hashvalue = myHash(str);
if (hash2pos.count(hashvalue) > 0) {
if (str[0] == '[')
cout << dicts[hash2pos[hashvalue]] << endl;
else {
string res = dicts[hash2pos[hashvalue]];
res = res.substr(1, res.size()-2);
cout << res << endl;
}
}
else
cout << "what?" << endl;
}
}