1078. Hashing (25)
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 15Sample Output:
0 1 4 -
题目的意思是给你一个数组,把每个数组用Hash映射一下啊。映射函数题目给了。
问题是Hash匹配中有一个二次搜索再散列,题目中只提到了这句话,这个还得自己百度一下。
二次搜索再散列是由于Hash匹配会冲突导致的,,也就是2个关键字处理函数的结果映射在了同一位置上
#include <iostream> #include <string.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <algorithm> using namespace std; const int maxn=1e5; int msize,n; int tag[maxn+5]; int prime[maxn+5]; bool check[maxn+5]; int num[maxn+5]; int tot; void eular() { memset(check,false,sizeof(check)); tot=0; for(int i=2;i<=maxn+5;i++) { if(!check[i]) prime[tot++]=i; for(int j=0;j<tot;j++) { if(i*prime[j]>maxn+5) break; check[i*prime[j]]=true; } } } int main() { eular(); scanf("%d%d",&msize,&n); for(int i=1;i<=n;i++) scanf("%d",&num[i]); for(int i=0;i<tot;i++) { if(prime[i]>=msize) { msize=prime[i]; break; } } memset(tag,0,sizeof(tag)); for(int i=1;i<=n;i++) { int flag=0; for(int j=0;j<msize;j++) { int h=(num[i]+j*j)%msize; if(!tag[h]) { tag[h]=1; printf("%d",h); flag=1;break; } } if(!flag) printf("-"); if(i!=n) printf(" "); else printf(" "); } return 0; }