PTA 7-43 字符串关键字的散列映射(手写哈希表的平方探测法)

考点:

  • 字符串的哈希函数
  • 哈希冲突时采用平方探测法

给定一系列由大写英文字母组成的字符串关键字和素数P,用移位法定义的散列函数H(Key)将关键字Key中的最后3个字符映射为整数,每个字符占5位;再用除留余数法将整数映射到长度为P的散列表中。例如将字符串AZDEG插入长度为1009的散列表中,我们首先将26个大写英文字母顺序映射到整数0~25;再通过移位将其映射为3×32
​2
​​ +4×32+6=3206;然后根据表长得到,即是该字符串的散列映射位置。
发生冲突时请用平方探测法解决。

本题的考点在于,我们通过将字符串的最后三位计算出哈希值,然后使用平方探测法来避免冲突。

平方探测法:

平方探测法当遇到冲突的时候,考虑的下一个位置不是线性探测法的递增,而是有两种情况:

  1. hashVal + i * i 向前看
    当新的 hashVal >= P 时,通过求余映射到 P nei
    hashVal %= P
  2. hashVal - i * i 向后看
    当新的 hashVal >= P 时,通过求余映射到 P 内
    hashVal += P 直到 hashVal > 0

同时,我们可以采用 map<string, int> 来保存每个字符串对应的位置,之后如果需要使用,直接取出用即可。

完整代码如下:

#include <iostream>
#include <cstring>
#include <map>
#include <string>
using namespace std;

#define MAXN 2000
#define MAXNUM (long long)1e14 + 1

int N, P;
string str;            // 临时保存读取的字符串
bool hashTable[MAXN];  // 哈希表
map<string, int> isIn; // 记录每个字符串的位置

int getHashVal(string str)
{ // 字符串转为整型
    int sum = 0;
    int len = str.size();
    for (int i = max(0, len - 3); i < len; i++)
    {
        sum = sum * 32 + str[i] - 'A';
    }
    return sum;
}

int main()
{
    fill(hashTable, hashTable + MAXN, false);
    scanf("%d%d", &N, &P);
    int pos, next;
    for (int i = 0; i < N; i++)
    {
        cin >> str;
        int hashVal = getHashVal(str) % P; // 获得哈希值
        if (isIn.find(str) == isIn.end()) // 如果没有保存过这个值
        {
            pos = hashVal;
            int j = 1;
            while (hashTable[pos] == true) // 如果有人占用了这个位置,直到找到一个没人用的位置
            {                              // 平方探测
                next = pos + j * j;
                if (next >= P)
                    next %= P;
                if (hashTable[next] == false)
                {
                    pos = next;
                    break;
                }
                next = pos - j * j;
                while (next < 0)
                    next += P;
                if (hashTable[next] == false)
                {
                    pos = next;
                    break;
                }
                j++;
            }
            if (i > 0)
                printf(" %d", pos);
            else
                printf("%d", pos);
            hashTable[pos] = true;
            isIn[str] = pos;
        }
        else
        {
            printf(" %d", isIn[str]);
        }
    }

    return 0;
}
posted @ 2020-04-11 12:13  南风sa  阅读(442)  评论(0编辑  收藏  举报