首页 > 学院 > 开发设计 > 正文

PAT 1078.Hashing (25)

2019-11-08 03:00:02
字体:
来源:转载
供稿:网友

题目: 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 - 题意:给出散列表Tsize和想要插入的元素, 将这些元素按读入的顺序插入散列表中,其中散列函数H(key) = key%Tsize,解决冲突采用正向增加的二次探查法,此外,如果题目给出的Tsize不是素数,那么需要将Tsize重新赋值一个比Tsize大的素数再进行元素插入。

代码:

#include <iostream>#include <cstdio>#include <cmath>using namespace std;const int maxn = 10007 + 10;bool flag[maxn] = {false};bool isPrime(int x) { if(x <= 1) return false; int midNumber = (int)sqrt(x*1.0); for(int i = 2; i <= midNumber; i++) { if(x%i == 0) return false; } return true;}int main(){ int Msize, N; scanf("%d%d", &Msize, &N); while(true) { if(isPrime(Msize)) break; else { Msize++; } } int input; int indexNumber = 0; for(int i = 0; i < N; i++) { scanf("%d", &input); int mod = input%Msize; if(flag[mod] == false) { flag[mod] = true; if(indexNumber == 0) { printf("%d", mod); } else { printf(" %d", mod); } indexNumber++; } else { int j = 1; for(; j <= Msize; j++) { int v = (input + j * j)%Msize; if(flag[v] == false) { flag[v] = true; if(indexNumber == 0) { printf("%d", v); } else { printf(" %d", v); } indexNumber++; break; } } if(j > Msize) { if(indexNumber == 0) printf("-"); else printf(" -"); } } } printf("/n"); return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表