浙大机试2014:1078. Hashing (25)

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 <stdio.h>#include <stdlib.h>int isPrime(int x){int i;if(x==1) return 0;if(x==2) return 1;for(i = 2;i <= (x>>1);i++){if(x%i==0)return 0;}return 1;}int reMSize(int x){int i;for(i = x;;++i){if(isPrime(i))return i;}}int main(){int MSize,N,i,in,tmp_in,j;int *ht;int *inp;scanf("%d%d",&MSize,&N);MSize = reMSize(MSize);ht = (int *)malloc(MSize*sizeof(int));inp = (int *)malloc(MSize*sizeof(int));for(i = 0;i < MSize;i++){ht[i] = 0;}for(i = 0;i < N;i++){scanf("%d",&inp[i]);}for(i = 0;i < N;i++){if(i != 0) printf(" ");in = inp[i] % MSize;if(ht[in] == 0){ht[in] = inp[i];printf("%d",in);}else{j = 1;tmp_in = in;while(ht[in]!=0 && j <= (MSize>>1) ){in = tmp_in;in = (in + j * j + MSize) % MSize;while(in < 0)in = (in + MSize) % MSize;if(ht[in]==0){ht[in] = inp[i];printf("%d",in);break;}//in = tmp_in;//in = (in – j * j + MSize) % MSize;//while(in < 0)//in = (in + MSize) % MSize;//if(ht[in]==0){//ht[in] = inp[i];//printf("%d",in);//break;//}j++;}if(j > (MSize>>1))printf("-");}}free(ht);free(inp);//int a;// while(1){// scanf("%d",&a);// printf("%d\n",isPrime(a));// }return 0;}

,何不去远方!昆明呀——赶一个花海;

浙大机试2014:1078. Hashing (25)

相关文章:

你感兴趣的文章:

标签云: