首页 > 代码库 > PAT 1078 Hashing

PAT 1078 Hashing

# include <stdio.h>
# include <algorithm>
# include <string.h>
# include <iostream>
# include <math.h>
using namespace std;
int prime[10100];
int vis[10110];
int cot;
void init_prime()
{
    memset(vis,0,sizeof(vis));
    cot=0;
    for(int i=2; i<=10100; i++)
    {
        if(!vis[i])
        {
            prime[cot++]=i;
            for(int j=i*2; j<=10100; j+=i)
                vis[j]=1;
        }
    }
}
int main()
{
    int n,size1,i,a,ans,j;
    int map[10100];
    while(~scanf("%d%d",&size1,&n))
    {
        init_prime();
        memset(map,0,sizeof(map));
        for(i=0; i<cot; i++)
        {
            if(prime[i]>=size1)
            {
                size1=prime[i];
                break;
            }
        }
        for(i=0; i<n; i++)
        {
            scanf("%d",&a);
            ans=a%size1;
            if(!map[ans])
            {
                if(i==0)
                    printf("%d",ans);
                else
                    printf(" %d",ans);
                map[ans]=1;
            }
            else/*二次探测法的公式: hi=(h(key)+i*i)%size1 1≤i≤size1-1 //即di=i2
                               即探查序列为d=h(key),d+1^2,d+2^2,…d+(size1-1)^2*/
            {
                for(j=1; j<size1; j++)
                {
                    int kk=(ans+j*j)%size1;
                    if(!map[kk])
                    {
                        map[kk]=1;
                        if(i==0)
                            printf("%d",kk);
                        else
                            printf(" %d",kk);
                        break;
                    }
                }
                if(j==size1)
                {
                    if(i==0)
                        printf("-");
                    else
                        printf(" -");

                }
            }
        }
        printf("\n");
    }
    return 0;
}

PAT 1078 Hashing