注意判定是否为素数时应该是小于等于,这个地方容易出错
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
const int maxn=10100;
bool isP(int n)
{
int a=(int)sqrt(1.0*n);
if(n<=1)
return false;
else
{
for (int i=2;i<=a;i++)
{
if(n%i==0)
return false;
}
}
return true;
}
int main()
{
int n,m,Tsize,a,hashTable[maxn]={0};
cin>>n>>m;
while (isP(n)==false)
{
n++;
}
Tsize=n;
for(int i=0;i<m;i++)
{
scanf("%d",&a);
int temp=a%Tsize;
if(hashTable[temp]==0)
{
printf("%d",temp);
hashTable[temp]++;
}
else
{
int j;
for (j=1;j<Tsize;j++)
{
temp=(a+j*j)%Tsize;
if(hashTable[temp]==0)
{
printf("%d",temp);
hashTable[temp]++;
break;
}
}
if(j==Tsize)
{
printf("-");
}
}
if(i!=m-1)
printf(" ");
}
}
本文介绍了一个使用素数探测技术优化哈希表冲突解决的算法实现。通过寻找大于输入n的最近素数作为哈希表大小,确保了哈希函数的均匀分布,减少冲突。对于每个插入操作,如果初始位置已占用,则采用二次探测法找到下一个可用位置。当遍历整个哈希表仍未找到空位时,输出特殊标记表示失败。
6320

被折叠的 条评论
为什么被折叠?



