Question connection: http://codevs.cn/problem/1230/
To put it bluntly, we need to manually write the data structure of a hash table to implement the addition and search functions. MAP can also be used directly (I used map to lie to AC for the first time)
I personally understand the implementation of hash tables (the linear addressing method is described below). If there are any mistakes, please kindly advise.
Use an array to simulate a hash table. The function f (x) = Number X indicates the minimum possible value of the lower mark in the hash table. Generally, f (x) = x mod t, T is the length of the hash table.
The following is an example of a hash table. If the pointer goes out of the end point of the hash table during the hash table traversal, it will start to retraverse the hash table.
Each time a number X is added to the hash table, it is searched from the subscript f (x). The Traversal method described above is searched until a hash table element containing the number X is found, the query is successful (X is included in the hash table ). If an element in an empty hash table is encountered during the traversal process, a search failure is returned (there is no X in the hash table ).
The process of inserting an element is similar to searching. when inserting the number X into a hash table, you first start searching from the subscript f (x) until you find the first hash table element with 0, insert the number X.
Below is the code for this question:
# Include <iostream> # include <stdio. h> # include <stdlib. h> # include <string. h >#include <algorithm> # define maxn 1000008 # define mod 1000007 using namespace STD; int hashtable [maxn]; void Update (int x) // Add the number X to the hash table {int num = x; X % = MOD; while (1) {If (! Hashtable [x]) {hashtable [x] = num; return;} If (hashtable [x]! = Num) {x ++; If (x = maxn) x = 0;} else return ;}} bool query (int x) // check whether the number X {bool found = false; int num = x; X % = MOD; while (1) {If (! Hashtable [x]) return false; If (hashtable [x]! = Num) {x ++; If (x = maxn) x = 0;} else return true;} int main () {int n, m, X; scanf ("% d", & N, & M); For (INT I = 1; I <= N; I ++) {scanf ("% d ", & X); Update (x + 1) ;}for (INT I = 1; I <= m; I ++) {scanf ("% d", & X ); if (query (x + 1) printf ("Yes \ n"); else printf ("NO \ n");} return 0 ;}
Zookeeper
[Codevs 1230] element search (handwritten hash table)