题目描述
定义哈希函数为H(key) = key%11。输入表长(大于、等于11),输入关键字集合,用线性探测再散列构建哈希表,并查找给定关键字。
--程序要求--
若使用C++只能include一个头文件iostream;若使用C语言只能include一个头文件stdio
程序中若include多过一个头文件,不看代码,作0分处理
不允许使用第三方对象或函数实现本题的要求
输入
测试次数t
每组测试数据为:
哈希表长m、关键字个数n
n个关键字
查找次数k
k个待查关键字
输出
对每组测试数据,输出以下信息:
构造的哈希表信息,数组中没有关键字的位置输出NULL
对k个待查关键字,分别输出:0或1(0—不成功,1—成功)、比较次数、查找成功的位置(从1开始)
样例输入
1
12 10
22 19 21 8 9 30 33 4 15 14
4
22
56
30
17
样例输出
22 30 33 14 4 15 NULL NULL 19 8 21 9
1 1 1
0 6
1 6 2
0 1
#include<iostream> #include<string> #include<queue> using namespace std; const int MaxLen = 20; class Map { private: bool vist[MaxLen]; int matrix[MaxLen][MaxLen]; int vexnum; void BFS(int v); public: void setmatrix(int vnum, int mx[MaxLen][MaxLen]); void BFSTraverse(); }; void Map::setmatrix(int vnum, int mx[MaxLen][MaxLen]){ int i, j; vexnum = vnum; for (i = 0; i < MaxLen; i++) for (j = 0; j < MaxLen; j++) matrix[i][j] = 0; for (i = 0; i < vexnum; i++) for (j = 0; j < vexnum; j++) matrix[i][j] = mx[i][j]; } void Map::BFSTraverse(){ BFS(0); } void Map::BFS(int v){ int w, u; int i, k; int *adjvex = new int[vexnum]; queue<int> Q; for (i = 0; i < vexnum; i++) vist[i] = false; for (v = 0; v < vexnum; ++v) { if (!vist[v]) { vist[v] = true; cout << v << " "; Q.push(v); while (!Q.empty()) { u = Q.front(); Q.pop(); k = 0; for (i = 0; i < vexnum; i++) { if (matrix[u][i] == 1) adjvex[k++] = i; } i = 0; for (w = adjvex[i]; w >= 0; w = adjvex[i++]) if (!vist[w]) { vist[w] = true; cout << w << " "; Q.push(w); } } } } } int main(){ int t,key=11; cin >> t; while(t--) { int m, n; cin >> m >> n; int *a = new int[m]; int *flag = new int[m];//用来标记这个位置有没有值 int i; for (i = 0; i < m; i++) flag[i] = -1; for (i = 0; i < n; i++) { int yu,x; cin >> x; yu = x % key; if (flag[yu] == -1) { a[yu] = x; flag[yu] = 1; } else { while (1) { if (flag[yu] == -1)//找到一个空位置 { a[yu] = x; flag[yu] = 1; break; } yu++; yu = yu % m; } } } for (i = 0; i < m - 1; i++) { if (flag[i] == -1) cout << "NULL" << " "; else cout << a[i] << " "; } if (flag[i] == -1) cout << "NULL" << endl; else cout << a[i] << endl; int k; cin >> k; while (k--) { int x,count = 0, loc; cin >> x; int yu = x % 11; int find = 0; while (true) { if (flag[yu] == -1) { count++; break; } if (a[yu] == x) { count++; loc = yu; find = 1; break; } count++; yu++; yu = yu % m; } if (find) cout << find << " " << count << " " << loc+1 << endl; else cout << find << " " << count << endl; } } }