Note
-
散列
-
“Quadratic probing (with positive increments only) is used to solve the collisions.”
二次探测 (只有正的增量) 用于解决碰撞 -
根据平方探查法:
如果hashTable里面key % size的下标对应的hashTable为false,说明这个下标没有被使用过,直接输出。否则step步长从1加到size-1,一次次尝试是否能使index = (key + step * step) % size; 所对应的位置没有元素,如果都没有找到就输出“-”,否则就输出这个找到的元素的位置。
Code:
#include<bits/stdc++.h>
using namespace std;
bool is_prime(int a){
if(a<=1) return false;
for(int i=2;i<=(int)sqrt(a);i++)
if(a%i==0) return false;
return true;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("data.txt","r",stdin);
#endif
int m,n,tt;
cin>>m>>n;
while(is_prime(m)==false) m++;
int hash[m];
memset(hash,0,sizeof(hash));
for(int i=0;i<n;i++){
cin>>tt;
if(i!=0) cout<<" ";
if(hash[tt%m]==0){
hash[tt%m]=1;
cout<<tt%m;
}
else{
int flag=0;
for(int j=1;j<m;j++){
if(hash[(tt+j*j)%m]==0){
flag=1;
hash[(tt+j*j)%m]=1;
cout<<(tt+j*j)%m;
break;
}
}
if(flag==0) cout<<"-";
}
}
return 0;
}