Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
根据给定的一系列整数关键字和素数p,用除留余数法定义hash函数H(Key)=Key%p,将关键字映射到长度为p的哈希表中,用线性探测法解决冲突。重复关键字放在hash表中的同一位置。
Input
连续输入多组数据,每组输入数据第一行为两个正整数N(N <= 1500)和p(p >= N的最小素数),N是关键字总数,p是hash表长度,第2行给出N个正整数关键字,数字间以空格间隔。
Output
输出每个关键字在hash表中的位置,以空格间隔。注意最后一个数字后面不要有空格。
Sample Input
5 5
21 21 21 21 21
4 5
24 15 61 88
4 5
24 39 61 15
5 5
24 39 61 15 39
Sample Output
1 1 1 1 1
4 0 1 3
4 0 1 2
4 0 1 2 0
Hint
Source
xam
#include <iostream>
using namespace std;
int const len = 1505;
int main()
{
int n, p;
while (cin >> n >> p)
{
/*int a[25];
for (int i = 0; i < n; i++)
cin >> a[i];*/
int a[len];
int *hash = new int[len]();
for (int i = 0; i < n; i++)
{
int d = 0;
cin >> a[i];
int t = a[i] % p;
if (!hash[t])//位置为空,就把数存入
{
hash[t] = a[i];
cout << t;
}
else//不为空,存在冲突,开始线性探测
{
//线性探测
bool visit;
int tp;//存储位置记录
while (hash[(t + d) % p])//开始探测不为空的位置
{
visit = false;
if (hash[(t + d) % p] == a[i])//找到已经存在的位置
{
tp = (t + d) % p;
visit = true;
break;//找出后必须立即跳出
}
d++;//线性寻找
}
//经过while探测后,找到为空的位置
hash[(t + d) % p] = a[i];
if (visit)//已经存在输出存在的
cout << tp;
else//不存在,输出新的位置
cout << (t + d) % p;
}
if (i == n - 1)
cout << endl;
else
cout << " ";
}
}
system("pause");
return 0;
}
改进后
#include <iostream>
using namespace std;
int const len = 1505;
int main()
{
int n, p;
while (cin >> n >> p)
{
/*int a[25];
for (int i = 0; i < n; i++)
cin >> a[i];*/
int a[len];
int *hash = new int[len]();
for (int i = 0; i < n; i++)
{
int d = 0;
cin >> a[i];
int t = a[i] % p;
if (!hash[t])//位置为空,就把数存入
{
hash[t] = a[i];
cout << t;
}
else//不为空,存在冲突,开始线性探测
{
//线性探测
bool visit;
while (hash[(t + d) % p])//开始探测不为空的位置,直到找到已有相同数据或空的位置
{ //线性查找,可能有两种结果,
//一是,已经存在同样的数,
//二是找到一个新的空位
visit = false;
if (hash[(t + d) % p] == a[i]) {
int tp = (t + d) % p;
cout << tp;
visit = true;
break;//找出后必须立即跳出
}
d++;//线性寻找
}
//经过while探测后,之前不存在这个数据,找到为空的位置
if (!visit)
{
hash[(t + d) % p] = a[i];
cout << (t + d) % p;
}
}
if (i == n - 1)
cout << endl;
else
cout << " ";
}
}
system("pause");
return 0;
}