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 -
题目大意:给定一个哈希表的大小,如果不是素数,则把它转换为比这个数大的第一个素数,作为哈希表的大小。然后给定n个数,存入哈希表中,并用二次探测法(只取正的)解决哈希冲突。如果可以存入,输出哈希值;否则输出“-”。
思路:建表、插入元素。
ps:
- 给出的最大M值为10000,所以在求素数的时候,范围要比10000大。
- 在判断是否为素数时,要考虑是否为1:如果为1,直接返回2。
- 是我自己遇到的问题:我最开始写的时候每次都从当前哈希值进行平方探测,而实际的应该是从最初的哈希值进行平方探测。。。
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct htlnode* hashtable;
struct htlnode
{
int size;
int *a;
};
int isprime(int x)
{
int i;
for(i=2; i*i<=x; i++)
if(x%i == 0) return 0;
return 1;
}
int nextprime(int n)
{
if(n == 1) return 2;/* 要特判一下,否则第二个点过不了 */
if(isprime(n)) return n;
int x = (n%2)?n+2:n+1, i;/* 取比x大的第一个奇数 */
while(x <= 20000)
{
if(isprime(x)) return x;
x += 2;
}
}
hashtable create(int maxsize)
{
hashtable h = (hashtable)malloc(sizeof(struct htlnode));
h->size = nextprime(maxsize);
h->a = (int*)malloc(h->size*sizeof(int));
int i;
for(i=0; i<h->size; i++) h->a[i] = -1;/* -1表示没有存数据 */
return h;
}
int Hash(int x,int p)
{
return x % p;
}
int Insert(hashtable h, int x)
{
int pos = Hash(x, h->size);
if(h->a[pos] == -1) h->a[pos] = 1;
else
{
int i;
for(i=1; i<=h->size/2; i++)/* 探测到size/2就不用再探测了:因为这个范围足以探测到所有的哈希值了 */
{
pos = Hash(x+i*i, h->size);/* 这里我最开始写的是pos+i*i,所以一直过不了... */
if(h->a[pos] == -1)
{
h->a[pos] = 1;
break;
}
}
if(i > h->size/2) pos = -1;
}
return pos;
}
int main()
{
int n, i, x, maxsize;
scanf("%d%d", &maxsize, &n);
hashtable h = create(maxsize);
for(i=0; i<n; i++)
{
scanf("%d", &x);
int pos = Insert(h, x);
if(pos == -1) printf("-");
else printf("%d", pos);
printf("%c", i == n-1?'\n':' ');
}
return 0;
}