浙大pat | 牛客网甲级 1013 Hashing (25) 哈希表

题目描述

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值