7-21 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 15
Sample Output:
0 1 4 - code:
#include <stdio.h> #include <string.h> #include <stdlib.h> struct HTable{ int *List; int Size; }; typedef struct HTable* HashTable; int prime[100000]; void is_Prime(){//筛选法求素数 int i,j; for(i = 0; i < 100000; i++){ prime[i] = 1; } prime[0] = prime[1] = 0; for(i = 2; i < 100000; i++){ if(prime[i]){ for(j = i+i; j < 100000; j += i){ prime[j] = 0; } } } } int NextPrime(int n){ if(!prime[n]){//如果不是素数 int i = n+1; while(!prime[i]){//一直加直到出现第一个素数 i++; } return i; } } HashTable Creat(int n){ HashTable H;//创建结构体并初始化 int i; H = (HashTable)malloc(sizeof(struct HTable)); H->Size = NextPrime(n); H->List = (int*)malloc(H->Size*sizeof(int)); for(i = 0; i < H->Size; i++) H->List[i] = 0; return H; } int Insert(HashTable H,int num){ int pos,i; pos = num % H->Size; for(i = 0; i <= H->Size && H->List[pos]; i++)//如果H->List[pos]这个点是0,则直接插入不执行循环,如果发现这个位置已经有了,则进行二次查找 pos = (pos + 2*i + 1) % H->Size; if(i <= H->Size){//如果在哈希表大小范围内找到新位置,返回新位置 H->List[pos] = 1; return pos; } else return -1;//如果在大小范围内找不着合适位置,返回-1 } int main(){ is_Prime(); int i,m,n,num;//m是大小,n是所给元素个数,num是每次输入的元素 int pos[10001];//记录哈希出来的位置 HashTable H; scanf("%d%d",&m,&n); H = Creat(m);//创建一大小为m的哈希表 for(i = 0; i < n; i++){ scanf("%d",&num); pos[i] = Insert(H,num);//哈希 } if(n){ printf("%d",pos[0]); for(i = 1; i < n; i++){ if(pos[i] == -1)printf(" -");//如果值是-1.输出- else printf(" %d",pos[i]); } } return 0; }