數據結構實驗之查找五:平方之哈希表

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a,b,i,m,d,flag,bb;
    int has[600];
    while(cin>>a>>b)
    {
        memset(has,0,sizeof(has));
            for(i=1;i<=a;i++)
            {
                    cin>>m;
                    bb=m%b;
                    if(has[m%b]==0||has[m%b]==m)
                    {
                        has[m%b]=m;
                        cout<<m%b;
                    }
                    else
                    {
                        flag=1;
                        d=1;
                        int k=m%b;
                        while(has[k]!=0)
                        {
                            k=(bb+flag*d*d)%b;
                           flag=-flag;
                           if(flag==1)
                           {
                               d++;
                           }
                            if(has[k]==m)
                            {
                                break;
                            }
                        }
                        has[k]=m;
                        cout<<k;
                    }
                if(i==a)
                {
                    cout<<endl;
                }
                else
                {
                    cout<<" ";
                }
            }

    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章