您的位置:首页 > 其它

HDU - 1880 字符串哈希

2017-04-09 11:08 357 查看

题意:

题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=1880

通过咒语查找功能,通过功能查找咒语。

思路:

字符串哈希模板题

代码:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 210000;
const int MOD = 100007;

struct Node {
Node* nxt;      // 后继指针
char str[100];   // 保存字符串
};

struct StrHash {

Node Hash[MAXN], *head[MOD], *cur;      // head数组记录同一哈希值的字符串的地址链表

void init() {
cur = Hash;
memset(head, 0, sizeof(head));
}

unsigned int BKDHash(char* s) {         // 计算哈希值
unsigned int seed = 131, res = 0;
while (*s) res = res * seed + *s++;
return (res & 0x7FFFFFFF) % MOD;
}

int getId(char* s) {                    // 从0开始依次将字符串插入hash数组,并计算哈希值,维护head链表
int code = BKDHash(s);
Node* ptr = head[code];
while (ptr) {
if (strcmp(ptr->str, s) == 0)
return ptr - Hash;
else ptr = ptr->nxt;
}
strcpy(cur->str, s);
cur->nxt = head[code];
head[code] = cur++;
return cur - Hash - 1;
}

int Find(char* s) {         // 通过s的哈希值,找到head链表首部。然后遍历链表找到字符串在hash数组中的位置
int code = BKDHash(s);
Node* ptr = head[code];
while (ptr) {
if (strcmp(ptr->str, s) == 0)
return ptr - Hash;
else ptr = ptr->nxt;
}
return -1;
}

} strhash;

char s[100], *p;

int main() {
//freopen("in.txt", "r", stdin);
strhash.init();
while (scanf("%s", s), s[0] != '@') {
strhash.getId(s); getchar();
gets(s);
strhash.getId(s);
}
int q;
scanf("%d", &q); getchar();
while (q--) {
gets(s);
int id = strhash.Find(s);
if (id == -1) puts("what?");
else {
p = strhash.Hash[id ^ 1].str;   // 对本题来说,两个相关的字符串互为奇偶
if (p[0] != '[') puts(p);
else {
p++;
while (*p != ']') putchar(*p++
);
puts("");
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm 字符串哈希