pat 甲1078 Hashing

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=100010;
bool p[maxn]={0};
int prime[maxn],pnum=0;
void prime_make()//筛法求素数
{
    for(int i=2;i<maxn;i++)
    {
        if(p[i]==0)
        {
            prime[pnum++]=i;
            for(int j=i+i;j<maxn;j=j+i)
            {
                p[j]=1;
            }
        }
    }
}
int main()
{
    int m,n;
    p[1]=1;
    int i=0,length,temp,j=1,thenum;
    bool z[10010]={0};
    cin>>m>>n;
    prime_make();
    if(p[m]==1)//求表长
    {
        while(prime[i]<m)
        {
            i=i+1;
        }
        length=prime[i];
    }
    else
    {
        length=m;
    }
    for(i=0;i<n;i++)//对每个数判断能否插入
    {
        cin>>thenum;
        j=0;
        temp=thenum%length;
        while(z[temp]==1)//hash表对应项有元素,则采用二次探查法解决
        {//推出循环则说明找到可插入项
            temp=(thenum+j*j)%length;
            if(j>=length)break;//无法插入
            j=j+1;
        }
        if(z[temp]==0)//有空位
        {
            z[temp]=1;
            if(i>0)//非首元素
            {
                cout<<" "<<temp;
            }
            else//首元素
            {
                cout<<temp;
            }
        }
        else//无空位
        {
            if(i>0)//非首元素
            {
                cout<<" -";
            }
            else//首元素
            {
                cout<<"-";
            }
        }
    }
   // cout<<length<<endl;
    return 0;
}

发布了22 篇原创文章 · 获赞 0 · 访问量 254

猜你喜欢

转载自blog.csdn.net/chang_sheng1/article/details/104083603