题目描述
定义哈希函数为H(key) = key%11。输入表长(大于、等于11),输入关键字集合,用二次探测再散列构建哈希表,并查找给定关键字。
输入
测试次数t
每组测试数据格式如下:
哈希表长m、关键字个数n
n个关键字
查找次数k
k个待查关键字
输出
对每组测试数据,输出以下信息:
构造的哈希表信息,数组中没有关键字的位置输出NULL
对k个待查关键字,分别输出:
0或1(0—不成功,1—成功)、比较次数、查找成功的位置(从1开始)
样例输入
1 12 10 22 19 21 8 9 30 33 4 41 13 4 22 15 30 41
样例输出
22 9 13 NULL 4 41 NULL 30 19 8 21 33 1 1 1 0 3 1 3 8 1 6 6
提示
#include<iostream> using namespace std; #define INF -9999 int main() { int T; cin>>T; while(T--) { int m,n; cin>>m>>n; int *array=new int[m]; for(int i=0;i<m;i++) array[i]=INF; for(int i=0;i<n;i++) { int num; cin>>num; if(array[num%11]==INF) { array[num%11]=num; } else { int di=0; int oper1=0; int oper2=0; while(true) { oper1=di*di; oper2=-di*di; while(oper1>m) { oper1-=m; } while(oper2<0) { oper2+=m; } if(array[(num%11+oper1)%m]==INF) { array[(num%11+oper1)%m]=num; break; } else if(array[(num%11+oper2)%m]==INF) { array[(num%11+oper2)%m]=num; break; } else di++; } } } for(int i=0;i<m;i++) { if(array[i]!=INF) cout<<array[i]; else cout<<"NULL"; if(i!=m-1) cout<<" "; } cout<<endl; int K; cin>>K; while(K--) { int di=0; int oper1=0; int oper2=0; int C; cin>>C; int times=0; while(true) { oper1=di*di; oper2=-di*di; while(oper1>m) oper1-=m; while(oper2<0) oper2+=m; times++; if(array[(C%11+oper1)%m]==C) { cout<<"1"<<" "<<times<<" "<<(C%11+oper1)%m+1<<endl; break; } if(di==0) { di++; continue; } times++; if(array[(C%11+oper2)%m]==C) { cout<<"1"<<" "<<times<<" "<<(C%11+oper2)%m+1<<endl; break; } if(di==m||array[(C%11+oper1)%m]==INF||array[(C%11+oper2)%m]==INF) { cout<<"0"<<" "<<times<<endl; break; } else di++; } } delete []array; } return 0; }
原文地址:https://www.cnblogs.com/SZU-DS-wys/p/12183048.html
时间: 2024-10-30 08:46:15