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 (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 (≤) and N (≤) 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 Data: 2019-05-13 20:16:33 3 Problem: PAT_A1078#Hashing 4 AC: 32:51 5 6 题目大意: 7 哈希表中插入一些不同的正整数,输出其插入的位置 8 哈希函数:H(key) = key%T,T为不小于MAX_SIZE的最小Prime 9 冲突处理:二次探测法 10 11 输入:给出M表长,N组输入 12 输出:给出插入位置,从0开始,无法插入打印“-” 13 */ 14 #include<cstdio> 15 #include<vector> 16 #include<algorithm> 17 using namespace std; 18 const int M=1e4+10; 19 int isPrime[M]; 20 21 void Euler() 22 { 23 fill(isPrime,isPrime+M,1); 24 isPrime[0]=0; 25 isPrime[1]=0; 26 vector<int> prime; 27 for(int i=2; i<M; i++) 28 { 29 if(isPrime[i]) 30 prime.push_back(i); 31 for(int j=0; j<prime.size(); j++) 32 { 33 if(i*prime[j] > M) 34 break; 35 isPrime[i*prime[j]]=0; 36 if(i%prime[j]==0) 37 break; 38 } 39 } 40 } 41 42 int main() 43 { 44 #ifdef ONLINE_JUDGE 45 #else 46 freopen("Test.txt", "r", stdin); 47 #endif // ONLINE_JUDGE 48 49 Euler(); 50 int n,m,x; 51 scanf("%d%d",&m,&n); 52 while(!isPrime[m]) 53 m++; 54 int h[M]={0}; 55 for(int i=0; i<n; i++) 56 { 57 scanf("%d", &x); 58 if(i!=0)printf(" "); 59 int k=0; 60 while(h[(x+k*k)%m]==1 && k<m) 61 k++; 62 if(h[(x+k*k)%m]==0) 63 { 64 printf("%d",(x+k*k)%m); 65 h[(x+k*k)%m]=1; 66 } 67 else 68 printf("-"); 69 } 70 71 return 0; 72 }
原文:https://www.cnblogs.com/blue-lin/p/10859009.html