poj2503 简单的hash

用闭散列,平方探测

用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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值