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 -
题目要求
给出大小为 MSize的序列以及一个哈希表的大小TSize
如果给定的 TSize不是素数的话,则找到大于它的最小素数作为哈希表的大小
然后利用H(key)=key%TSize求得key
如果key已经被 占用二次探测法,即index+i^2(i=0,1,2……)向后查找空位
最后输出每个序列在哈希表的下标key
解题思路
由于这里哈希表的大小不超过10^4,即对应的素数范围也不超过10^4
采用经典素数方法,也就是打表。先把每个位置是不是素数给统计出来
然后对于给定的TSize,用while循环不断加一直到为素数为止
确定了TSize后剩下就十分简单了,用a[i]表示哈希表的状态,a[i]=1表示key为1已经有元素了,对每个元素进行探测,直到找到位置存储。如果找不到则输出-
注意
1不是素数
完整代码
#include<bits/stdc++.h>
using namespace std;
#define maxsize 100000
int main(){
int n,m,i,j,k,t,max,a[100010],isprime[100010];
memset(a,0,sizeof(a));
for(i=2;i<maxsize;i++) isprime[i]=1;
for(i=2;i<maxsize;i++){
if(isprime[i]){
j=2;
while(i*j<maxsize){
isprime[i*j]=0;
j++;
}
}
}
cin>>m>>n;
while(!isprime[m]) m++;
for(i=0;i<n;i++){
cin>>t;
for(j=0;j<m;j++){
k=(t+j*j)%m;
if(a[k]==0){
a[k]=1;
cout<<k;
break;
}
}
if(j==m) cout<<"-";
if(i!=n-1) cout<<" ";
}
return 0;
}