用闭散列,平方探测
用hash函数求出外语字符串的地址,存放到table中。
对需要翻译的单词,到table中查找即可。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define TABLE_SIZE 200003
struct Node {
char key[12], fore[12];
bool flag;
Node () { flag = false; }
} table[TABLE_SIZE];
unsigned int BKDRHash(char *str)
{
unsigned int seed = 131;
unsigned int hash = 0;
while (*str)
{
hash = hash * seed + (*str++);
}
return (hash & 0x7FFFFFFF) % TABLE_SIZE;
}
void insert(char *s1, char *s2)
{
int pos = BKDRHash(s2), m = 0;
while (table[pos].flag) {
pos += 2 * (++m) - 1;
if (pos >= TABLE_SIZE) pos -= TABLE_SIZE;
}
strcpy (table[pos].key, s2);
strcpy (table[pos].fore, s1);
table[pos].flag = true;
}
int main()
{
char buff[50], s1[20], s2[20];
while (gets(buff) && buff[0] != '\0')
{
sscanf (buff, "%s %s", s1, s2);
insert (s1, s2);
}
while (scanf ("%s", s1) != EOF) {
int pos = BKDRHash(s1), m = 0;
bool flag = false;
while (table[pos].flag) {
if (strcmp(table[pos].key, s1) == 0) { printf ("%s\n", table[pos].fore); flag = true; break; }
else {
pos += 2 * (++m) - 1;
pos = (pos >= TABLE_SIZE ? pos - TABLE_SIZE : pos);
}
}
if (!flag) printf ("eh\n");
getchar();
}
return 0;
}