首页 > 学院 > 开发设计 > 正文

PAT A1078.Hashing(25)

2019-11-08 01:04:37
字体:
来源:转载
供稿:网友

1078. Hashing (25)

时间限制100 ms内存限制65536 kB代码长度限制16000 B判题程序Standard作者CHEN, Yue

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 410 6 4 15Sample Output:

0 1 4 -

#include<cstdio>#include<cmath>const int maxn=10010;bool isPrime(int a){	if(a<=1)		return false;//1不是质数要加上; 	int temp=sqrt(a);	for(int i=2;i<=temp;i++)		if(a%i==0)			return false;	return true;}bool sign[maxn]={false};int main(){	int Msize,n;	scanf("%d%d",&Msize,&n);	if(!isPrime(Msize))		for(Msize=Msize+1;!isPrime(Msize);Msize++)	;//修正Msize 			for(int i=0;i<n;i++)	{		int temp;		scanf("%d",&temp);		int H0=temp%Msize;				if(sign[H0]==false)		{			if(i)				printf(" ");			printf("%d",H0);			sign[H0]=true;		}		else		{			int H=H0,j=1;			while(sign[H]==true)//碰撞处理; 			{				H=(H0+j*j)%Msize;				j++;				if(j>10010)  //这里有5分,要大于Msize才可以通过 ; 					break;			}			if(j<=10010)			{				printf(" %d",H);				sign[H]=true;			}			else				printf(" -");		}	}	return 0;}注意的地方:

(1)1不是质数,有一个测试点 ;

(2)插入失败时,所选取的数要大于Msize,有个5分的测试点;

(3)PAT坚持刷题过半之后,明显感觉代码能力进步很大;


上一篇:遍历Map

下一篇:多媒体(拍照-录像)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表