给定多个魔咒以及对应的效果,要求对于后面的魔咒或效果,及时给出对应的效果或魔咒。
建立两张哈希表直接哈希就可以了。输入需要稍微处理一下。哈希函数计算出来的值要保证是正的,否则读数组会出错。
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; const int N = 100010; const int H = 100007; struct Node { char que[25]; char ans[85]; int next; }; Node nodeA[N], nodeB[N]; int curA, curB; int hashTableA[N], hashTableB[N]; void initHash() { for (int i = 0; i < H; ++i) { hashTableA[i] = -1; hashTableB[i] = -1; } curA = 0; curB = 0; } unsigned int getHash(char* str) { unsigned int seed = 131; unsigned int hash = 0; while (*str) { hash = hash * seed + *str++; } return (hash & 0x7fffffff) % H; } void insertHash(char* que, char* ans) { unsigned int h; h = getHash(que); strcpy(nodeA[curA].que, que); strcpy(nodeA[curA].ans, ans); nodeA[curA].next = hashTableA[h]; hashTableA[h] = curA; ++curA; h = getHash(ans); strcpy(nodeB[curB].que, que); strcpy(nodeB[curB].ans, ans); nodeB[curB].next = hashTableB[h]; hashTableB[h] = curB; ++curB; } int searchHashA(char* que) { unsigned int h = getHash(que); int next = hashTableA[h]; while (next != -1) { if (strcmp(que, nodeA[next].que) == 0) return next; next = nodeA[next].next; } return -1; } int searchHashB(char* ans) { unsigned int h = getHash(ans); int next = hashTableB[h]; while (next != -1) { if (strcmp(ans, nodeA[next].ans) == 0) return next; next = nodeB[next].next; } return -1; } int main() { char str[120], que[25], ans[85], qlen, alen; int n, res; initHash(); while (gets(str)) { if (str[0] == '@') break; qlen = 0; for (int i = 1; str[i] != ']'; ++i) { que[qlen++] = str[i]; } que[qlen] = 0; alen = 0; for (int i = qlen + 3; str[i] != 0; ++i) { ans[alen++] = str[i]; } ans[alen] = 0; insertHash(que, ans); } scanf("%d", &n); getchar(); while (n--) { gets(str); if (str[0] == '[') { qlen = strlen(str); str[qlen - 1] = 0; res = searchHashA(str + 1); if (res == -1) printf("what?\n"); else printf("%s\n", nodeA[res].ans); } else { alen = strlen(str); res = searchHashB(str); if (res == -1) printf("what?\n"); else printf("%s\n", nodeB[res].que); } } system("pause"); return 0; }