PAT1078 Hashing

11-散列2 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 TSizeis 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:

0 1 4 -


平法探测法的训练, 很基础


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define MAXTABLESIZE 100000

int IsPrime(int N);
int Find( int Size, int Key, int* Cells);

int main(){
    int M, N;
    int Tmp, i;
    int tmp;
    freopen( "C:\\in.txt", "r", stdin );
    scanf("%d %d", &M, &N);
    if( M>2)
        while(!IsPrime(M)) M++;
    else M = 2;
    int* Cells = (int*)malloc(M*sizeof(int));
    for(i = 0; i<M; i++) Cells[i] = 0;
    for(i = 0; i<N; i++){
        scanf("%d", &Tmp);
        tmp = Find( M, Tmp, Cells);
        if(tmp>=0)
            printf("%d", tmp);
        else printf("%c", '-');
        if(i!= N-1) printf(" ");
    }
    printf("\n");
    free(Cells);
    return 0;
}

int Find( int Size, int Key, int* Cells){
    int CurrentPos, NewPos;
    int CNum = 0;
    NewPos = Key%Size;
    if( !Cells[NewPos] ) 
        Cells[NewPos] = 1;
    else 
    {
        for( CNum = 1; CNum<Size; CNum++ ){
            CurrentPos = (NewPos+CNum*CNum)%Size;
            if( !Cells[CurrentPos] ){
                Cells[CurrentPos] = 1;
                NewPos = CurrentPos;
                break;
            }
        }
        if(CNum>=Size) NewPos = -1;
    }
    return NewPos;
}

int IsPrime(int N){
    int p;
    for( p = 2; p<=(int)sqrt(N); p++ ) {
        if(N%p == 0) {
            p = 0;
            break;
        }
    }
    return p;
}

 

posted @ 2015-11-17 12:32  鸡员外  阅读(497)  评论(0编辑  收藏  举报