PAT甲级——A1078 Hashing

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.

Input Specification:

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.

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 -

通过将给定元素值对表长的余数作为在哈希表中的插入位置,如果出现冲突,采用平方探查法解决。平方探查法的具体过程是,假设给定元素值为a,表长为M,插入位置为a%M,假设a%M位置已有元素,即发生冲突,则查找

(a+1^2)%M,(a-1^2)%M,(a+2^2)%M,(a-2^2)%M,⋯⋯(a+M^2)%M,(a-M^2)%M直至查找到一个可进行插入的位置,否则当查找到(a+M^2)%M,(a-M^2)%M仍然不能插入则该元素插入失败。

 1 #include <iostream>
 2 #include <vector>
 3 #include <cmath>
 4 using namespace std;
 5 int M, N;
 6 bool isPrime(int num)
 7 {
 8     if (num <= 3)
 9         return num > 1;
10     if (num % 6 != 1 && num % 6 != 5)
11         return false;
12     int s = (int)sqrt(num);
13     for (int i = 5; i <= s; ++i)
14         if (num % i == 0)
15             return false;
16     return true;
17 }
18 int main()
19 {
20     cin >> M >> N;
21     while (!isPrime(M++));//找到素数
22     M--;
23     vector<int>table(M, 0);
24     int num, index;
25     for (int i = 0; i < N; ++i)
26     {
27         cin >> num;
28         index = num % M;
29         if (table[index] > 0)//存在冲突
30         {
31             for (int i = 1; i <= M; ++i)
32             {
33                 index = (num + i * i) % M;
34                 if (table[index] == 0)
35                     break;        
36             }
37         }
38         if(table[index] == 0)//不存在冲突
39         {
40             table[index]++;
41             cout << index;
42         }
43         else
44             cout << "-";
45         if (i < N - 1)
46             cout << " ";
47     }
48     return 0;
49 }

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/11324490.html