题解
对前半部分和后半部分分别Hash,然后查询即可,用map保存hash值及其对应关系。
注意这题直接map < string,string > 会MLE。
在尝试过程中,可以用到的Hash值有,unsigned int 自然溢出,或者是 201326611、100663319,1e9+7,1e9+9
代码
unsigned int 自然溢出
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef unsigned int ui;
const int nmax = 150 ;
const int INF = 0x3f3f3f3f;
const ui MOD1 = 1e9 + 9;
const ui MOD2 = 1e9 + 9;
const ui p = 131;
int n, mcnt, fcnt;
char str[105];
char mis[100005][22], fun[100005][82];
map<ui, int> mp1, mp2;
inline ui hash1(char s[]) {
int len = strlen(s);
ui ans = s[0];
for (int i = 1; i < len; ++i) ans = ((ans * p) + s[i] ) ;
return ans;
}
inline ui hash2(char s[]) {
int len = strlen(s);
ui ans = s[0];
for (int i = 1; i < len; ++i) ans = ((ans * p) + s[i] ) ;
return ans;
}
int main() {
while (gets(str)) {
if (str[0] == '@') break;
int len = strlen(str), pos;
for (int i = 0; i < len; ++i) if (str[i] == ']') {pos = i; str[pos] = '\0'; break;}
strcpy(mis[mcnt], str + 1); strcpy(fun[fcnt], str + pos + 2);
mp1[hash1(mis[mcnt])] = fcnt;
mp2[hash2(fun[fcnt])] = mcnt;
fcnt++; mcnt++;
}
scanf("%d", &n); getchar();
char str[100];
for (int i = 1; i <= n; ++i) {
gets(str);
if (str[0] == '[') {
int len = strlen(str); str[len - 1] = '\0';
int ans = hash1(str + 1);
if (mp1[ans] == 0) printf("what?\n");
else printf("%s\n", fun[mp1[ans]]);
} else {
int ans = hash2(str);
if (mp2[ans] == 0) printf("what?\n");
else printf("%s\n", mis[mp2[ans]]);
}
}
return 0;
}