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:
#include <stdio.h>
#include <vector>
#include <string.h>
#include <math.h>
#include <iostream>
using namespace std;
int NextPrime ( int N ) {
if ( N == 1 ) //1既不是素数,也不是合数; 2是素数
return 2;
int i, p = ( N % 2 ) ? N + 2 : N + 1;
while (1) {
double q = p;
for ( i = sqrt(q); i > 2; i-- )
if ( !( p % i ) ) break;
if ( i == 2 ) return p;
else p += 2;
}
}
int IsPrime ( int n ) {
if ( n == 1 )
return 0;
else if ( n == 2 )
return 1;
else {
int k = sqrt(n);
for ( int i = 2; i <= k; i++ )
if ( n % i == 0 )
return 0;
return 1;
}
}
int tables[10009];
int main () {
int size,n,m,key,pos,k,tmp;
cin>>n>>m;
if(IsPrime(n))
{
size=n;
}else
{
size=NextPrime(n);
}
for(int i=0;i<size;i++)
tables[i]=0;
for ( int i = 0; i < m; i++ ) {
cin >> key;
pos = key % size;
k = 0; tmp = pos;
while ( k < size ) {
if ( tables[pos] == 0 ) {
tables[pos] = key;
cout << pos;
break;
}
else {
k++;
pos = ( tmp + k * k ) % size;
}
}
if ( k == size ) //没找到
cout <<"-";
if ( i != m - 1 )
{
cout <<" ";
}//最后一个元素后面不要空格
}
return 0;
}
本文介绍了一种使用二次探测解决冲突的哈希表插入算法。当用户定义的哈希表大小不是质数时,会自动调整为下一个质数。输入一系列不重复的正整数,程序将显示每个数在哈希表中的位置。
933

被折叠的 条评论
为什么被折叠?



