Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- When doing hashing:
- - pick a key big enough to make sure you won't have too many collisions
- - you can pick your key about 6 times bigger than the number of elements from the hash
- - pick a prime number key
- - pick a key small enough to make sure you won't waste too much memory on the list
- */
- /*
- You are given an array of N elements.
- You are also given M querys - each query has a value X
- For each X output "True" if X is in the initial array, or "False" if it isn't
- */
- /*
- FIRST SOLUTION:
- binary search
- - we should sort the N elements array (merge sort)
- - then binary search for each of the M elements in the original array.
- - Complexity: O(NlogN + MlogN) = O(logN * (N + M))
- */
- /*
- n = 5, m = 7
- v[] = 1 2 3 4 5
- 3 - True
- 4 - True
- 5 - True
- 2 - True
- 9 - False
- 6 - False
- 4 - True
- */
- /*
- SECOND SOLUTION:
- with hashing
- - read the N elements and insert all of them in your hash
- - read the M queryes and look up for each of them in your hash
- - Complexity: O(N + M)
- */
- #include <iostream>
- #include <vector>
- using namespace std;
- // total memory - KEY + N
- const int KEY = 666013;
- vector<int> H[KEY];
- void insert(int x) { // insert in the hash - O(1)
- int line = x % KEY;
- H[line].push_back(x);
- }
- bool query(int x) {
- int line = x % KEY;
- for (size_t i = 0; i < H[line].size(); ++i) {
- if (H[line][i] == x) {
- return true;
- }
- }
- return false;
- }
- int n, x;
- int m;
- int main() {
- cin >> n >> m; // read the number of elements in your array and the number of querys
- for (int i = 0; i < n; ++i) {
- cin >> x; // read your x
- insert(x); // insert your number x in the hash
- }
- for (int i = 0; i < m; ++i) { // for each of the m querys
- cin >> x;
- if (query(x) == true) {
- cout << "Number " << x << " is in the hash\n";
- } else {
- cout << "Number " << x << " is not in the hash\n";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement