题目描述
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.
输入描述:
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.
输出描述:
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.
输入例子:
4 4 10 6 4 15
输出例子:
0 1 4 -
这道题有两个注意点:
1.题目要求只取正向增量,若要考虑负向增量还需自己编写一个取模函数
2.平方探测法插入失败的条件是p>msize/2
1 #include<bits/stdc++.h> 2 using namespace std; 3 int arr[10005]; 4 int hash_table[100005]; //由于可能需要msize增加到质数,所以稍微开大一点 5 int msize,n; 6 /* 题目只需正增量,直接取余即可 7 int mod(int a,int b){ //取模 8 if (a>=0) 9 return a%b; 10 return (abs(a/b)+1)*b+a; 11 }*/ 12 bool prime(int x){ 13 if (x==1) 14 return false; 15 if (x==2) 16 return true; 17 for (int i=2;i<=x/2;++i){ 18 if (x%i==0){ 19 return false; 20 } 21 } 22 return true; 23 } 24 25 int insert(int x){ 26 int key=x%msize; 27 int p=0; 28 while(p<=msize/2){ 29 int index=(key+p*p)%msize; 30 if (hash_table[index]==-1){ //该空间未被占用 31 hash_table[index]=x; 32 return index; 33 } 34 ++p; 35 } 36 return -1; 37 } 38 int main(){ 39 cin>>msize>>n; 40 memset(hash_table,-1,sizeof(hash_table)); 41 for (int i=0;i<n;++i){ 42 cin>>arr[i]; 43 } 44 while(!prime(msize)){ 45 msize++; 46 } 47 for (int i=0;i<n;++i){ 48 int position=insert(arr[i]); 49 if (position==-1) 50 cout<<"-"; 51 else 52 cout<<position; 53 if (i!=n-1) 54 cout<<" "; 55 } 56 }
标签:prime,25,hash,int,msize,table,size,Hashing From: https://www.cnblogs.com/coderhrz/p/16729533.html