考點:
- 字符串的哈希函數
- 哈希衝突時採用平方探測法
給定一系列由大寫英文字母組成的字符串關鍵字和素數P,用移位法定義的散列函數H(Key)將關鍵字Key中的最後3個字符映射爲整數,每個字符佔5位;再用除留餘數法將整數映射到長度爲P的散列表中。例如將字符串AZDEG插入長度爲1009的散列表中,我們首先將26個大寫英文字母順序映射到整數0~25;再通過移位將其映射爲3×32
2
+4×32+6=3206;然後根據表長得到,即是該字符串的散列映射位置。
發生衝突時請用平方探測法解決。
本題的考點在於,我們通過將字符串的最後三位計算出哈希值,然後使用平方探測法來避免衝突。
平方探測法:
平方探測法當遇到衝突的時候,考慮的下一個位置不是線性探測法的遞增,而是有兩種情況:
hashVal + i * i
向前看
當新的 hashVal >= P 時,通過求餘映射到 P nei
hashVal %= P
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;
}