1078 Hashing (25分)
The task of this problem is simple: insert a sequence of distinct positive integers into a hash table, and output the positions of the input numbers. The hash function is defined to be H(key)=key%TSize where TSize is the maximum size of the hash table. Quadratic probing (with positive increments only) is used to solve the collisions.
Note that the table size is better to be prime. If the maximum size given by the user is not prime, you must re-define the table size to be the smallest prime number which is larger than the size given by the user.
Input Specification:
Each input file contains one test case. For each case, the first line contains two positive numbers: MSize (≤104) and N (≤MSize) which are the user-defined table size and the number of input numbers, respectively. Then N distinct positive integers are given in the next line. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print the corresponding positions (index starts from 0) of the input numbers in one line. All the numbers in a line are separated by a space, and there must be no extra space at the end of the line. In case it is impossible to insert the number, print "-" instead.
Sample Input:
4 4
10 6 4 15
Sample Output:
0 1 4 -
这题就是模拟哈希表,发生冲突时,采用二次方正向增长解决冲突。
Quadratic probing (with positive increments only) is used to solve the collisions.
英文不好,是硬伤。
第三、四测试点bug了一小时,最后发现是我素数表有问题!
for(i=2;i<100;i++){ for(j=2;j*i<r;j++){ prime[i*j]=false; } }
外层的i我开到20,结果一直报错!
经过测试,开到80就可以了
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int r=10111;
bool prime[r]={true};
int d[r],index[r],h[r],n,m;
void init(){
int i,j;
fill(prime,prime+r,true);
for(i=2;i<30;i++){
for(j=2;j*i<r;j++){
prime[i*j]=false;
}
}
prime[1]=false;
// for(i=1;i<r;i++){
// if(prime[i])
// cout<<i<<" ";
// }
}
void deal(){
int i,j,t;
for(i=0;i<m;i++){
t=d[i]%n;
if(h[t]==0){
h[t]=d[i];
index[i]=t;
}
else{
int step=1;
while(h[(d[i]+step*step)%n]!=0){
step++;
if(step>=n){
break;
}
}
if(step>=n){
index[i]=-1;
}
else{
index[i]=(d[i]+step*step)%n;
h[(d[i]+step*step)%n]=d[i];
}
}
}
}
int main(){
int i,j,t;
fill(index,index+r,-1);
fill(h,h+r,0);
init();
cin>>n>>m;
for(i=0;i<m;i++)
cin>>d[i];
if(prime[n]==false){
while(prime[n]!=true){
n++;
}
}
deal();
for(i=0;i<m;i++){
if(index[i]!=-1){
cout<<index[i];
}
else{
cout<<"-";
}
if(i<m-1)
cout<<" ";
}
cout<<endl;
return 0;
}
总结:
1.
Quadratic probing(二次探查法)
Quadratic probing (with positive increments only)
二次探测(正方向)
2.素数表外层开到80!