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 15Sample Output:
0 1 4 -
tips:注意两点,1.prime数组至少10008大小。大于10000的第一个素数是10007对应测试点二。
2.二次探查(仅用积极的增量)用于解决冲突。
二次探测法的公式: hi=(h(key)+i*i)%m 0≤i≤m-1 //即di=i^2
即探查序列为d=h(key),d+1^2,d+2^2,…,等。 如果认为(h(key)+i*i)<tsize是错误的。对应了测试点三。
#include<iostream> #include<cstring> using namespace std; int _hash[10008]; int tsize,n; int prime[100008]; int a[10008]; int flag[10008]; void isprime(){ memset(prime,1,sizeof(prime)); prime[1]=0; for(int i=2;i<=100000;i++){ if(prime[i]){ for(int j=2*i;j<=100000;j+=i){ prime[j]=0; } } } } int main() { isprime(); memset(flag,-1,sizeof(flag)); memset(_hash,-1,sizeof(_hash)); cin>>tsize>>n; while(!prime[tsize++]);tsize--; //cout<<tsize<<endl; for(int i=0;i<n;i++)scanf("%d",a+i); for(int i=0;i<n;i++){ int index=a[i]%tsize ; for(int k=0;k<tsize;k++){ int pos=(index+k*k)%tsize; //if(index+j>=tsize)break; if(_hash[pos]<0){ _hash[pos]=a[i]; flag[i]=pos; break; } } } if(flag[0]<0)cout<<"-";else cout<<flag[0]; for(int i=1;i<n;i++){ if(flag[i]<0)cout<<" -"; else cout<<" "<<flag[i]; } return 0; }