DS哈希查找—二次探测再散列
题目描述
定义哈希函数为 H ( k e y ) H(key) H(key) = k e y key key % 11 11 11。输入表长(大于、等于11),输入关键字集合,用二次探测再散列构建哈希表,并查找给定关键字。
输入
测试次数 t t t
每组测试数据格式如下:
哈希表长 m m m、关键字个数 n n n
n n n个关键字
查找次数 k k k
k k k个待查关键字
输出
对每组测试数据,输出以下信息:
构造的哈希表信息,数组中没有关键字的位置输出 N U L L NULL NULL
对k个待查关键字,分别输出:
0或1(0—不成功,1—成功)、比较次数、查找成功的位置(从1开始)
输入样例:
1
12 10
22 19 21 8 9 30 33 4 41 13
4
22
15
30
41
输出样例:
22 9 13 NULL 4 41 NULL 30 19 8 21 33
1 1 1
0 3
1 3 8
1 6 6
参考代码:
#include <iostream>
using namespace std;
void display(int *arr, int len) {
for (int i = 0; i < len; i++) {
if (arr[i] == 0)
cout << "NULL";
else
cout << arr[i];
if (i != len - 1)
cout << ' ';
}
cout << endl;
}
int main() {
int t;
cin >> t;
while (t--) {
int m, n;
cin >> m >> n;
int *Hash = new int[m];
for (int i = 0; i < m; ++i) {
Hash[i] = 0;
}
for (int i = 0; i < n; ++i) {
int num;
cin >> num;
int index = num % 11;
if (Hash[index] == 0 || Hash[index] == num) {
Hash[index] = num;
} else {
int oper = 0;
for (int j = 1;; ++j) {
oper = j * j;
while (oper > m)
oper -= m;
if (Hash[(index + oper) % m] == 0 || Hash[(index + oper) % m] == num) {
Hash[(index + oper) % m] = num;
break;
} else {
if ((index - oper) >= 0) {
if (Hash[index - oper] == 0 || Hash[index - oper] == num) {
Hash[index - oper] = num;
break;
}
} else {
if (Hash[m + (index - oper)] == 0 || Hash[m + (index - oper)] == num) {
Hash[m + (index - oper)] = num;
break;
}
}
}
}
}
}
display(Hash, m);
int k, search_time, val, key, flag;
cin >> k;
while (k--) {
search_time = 0, flag = 0;
cin >> val;
int index = val % 11;
key = index;
int symbol = 1;
int oper = 0;
for (int i = 1;;) {
search_time++;
if (Hash[index] == val) {
flag = 1;
cout << 1 << ' ' << search_time << ' ' << index + 1 << endl;
break;
} else if (Hash[index] == 0)
break;
oper = i * i;
while (oper > m) {
oper -= m;
}
if (symbol) {
symbol = 0;
index = (key + oper) % m;
} else {
symbol = 1;
index = key - oper;
if (index < 0)
index += m;
i++;
}
}
if (!flag) {
cout << 0 << ' ' << search_time << endl;
}
}
}
return 0;
}