PAT甲级——A1078 Hashing

Posted zzw1024

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 

 

以上是关于PAT甲级——A1078 Hashing的主要内容,如果未能解决你的问题,请参考以下文章

pat甲级没做出来没有分吗

pat甲级60分啥水平

pat可以直接考甲级吗

PAT甲级考前整理

pat甲级考试+pat1051+1056

菜鸟记录PAT甲级1003--Emergency