题目描述
The task of this problem is simple: insert a sequence ofdistinct positive integers into a hash table, and output the positions of theinput numbers. The hash function isdefined to be "H(key) = key % TSize" where TSize is the maximum sizeof 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-definethe table size to be the smallest prime number which is larger than the sizegiven by the user.
输入描述:
Each input file contains one test case. For each case, the first line contains twopositive numbers: MSize (<=104) and N (<=MSize) which are the user-defined table size andthe 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 aspace.
输出描述:
For each test case, print the corresponding positions (indexstarts from 0) of the input numbers in one line. All the numbers in a line are separated by aspace, and there must be no extra space at the end of the line. In case it is impossible to insert thenumber, print "-" instead.
输入例子:
4 4
10 6 4 15
输出例子:
0 1 4 -
首先这一题使用了哈希表,使用的是哈希表的除数取余法,但是后面的冲突处理方法使用了二次探测法,二次探测法大概是这个公式numi+1=numi+j*j,j=1,2,…n-1,n为哈希表的大小,不知道二次探测法的人感觉做不出来这道题
Quadratic是二次方程的意思,probe是探测的意思,collision是碰撞,冲突的意思,合起来就是冲突检查使用二次探测法,记住这个单词的意思
以后在涉及到找大于或者是小于某个数的最大或最小素数的时候使用双层循环判断素数就足够了!
#include <iostream>
#include <string>
#include <memory.h>
#include <math.h>
using namespace std;
int theHashing[10003];
int theNum[10003];
int Nsize,N;
bool checkThePrime(int n)
{
if(n==1) return false;
for(int i=2;i<=(int)sqrt(n);i++)
{
if(n%i == 0)return false;
}
return true;
}
int main()
{
int i,j;
int tmp;
int index;
cin>>Nsize>>N;
memset(theHashing,-1,sizeof(theHashing));
for(i=Nsize;;i++)
{
if(checkThePrime(i)) break;
}
Nsize=i;
for(i=0;i<N;i++)
{
cin>>theNum[i];
}
for(i=0;i<N;i++)
{
index = theNum[i]%Nsize;
for(j=0;j<Nsize;j++)
{
tmp = (index + j*j)%Nsize;
if(theHashing[tmp] == -1) break;
}
if(j==Nsize)
cout<<"-";
else {theHashing[tmp] =theNum[i]; cout<<tmp;}
if(i!=N-1)
cout<<" ";
}
return 0;
}