Advertisement
Guest User

Untitled

a guest
Apr 30th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. /*
  2. When doing hashing:
  3. - pick a key big enough to make sure you won't have too many collisions
  4.     - you can pick your key about 6 times bigger than the number of elements from the hash
  5. - pick a prime number key
  6. - pick a key small enough to make sure you won't waste too much memory on the list
  7. */
  8.  
  9. /*
  10. You are given an array of N elements.
  11. You are also given M querys - each query has a value X
  12. For each X output "True" if X is in the initial array, or "False" if it isn't
  13. */
  14.  
  15. /*
  16.     FIRST SOLUTION:
  17.     binary search
  18.     - we should sort the N elements array (merge sort)
  19.     - then binary search for each of the M elements in the original array.
  20.     - Complexity: O(NlogN + MlogN) = O(logN * (N + M))
  21. */
  22.  
  23. /*
  24. n = 5, m = 7
  25. v[] = 1 2 3 4 5
  26. 3 - True
  27. 4 - True
  28. 5 - True
  29. 2 - True
  30. 9 - False
  31. 6 - False
  32. 4 - True
  33. */
  34.  
  35. /*
  36.     SECOND SOLUTION:
  37.     with hashing
  38.     - read the N elements and insert all of them in your hash
  39.     - read the M queryes and look up for each of them in your hash
  40.     - Complexity: O(N + M)
  41. */
  42. #include <iostream>
  43. #include <vector>
  44. using namespace std;
  45.  
  46. // total memory - KEY + N
  47. const int KEY = 666013;
  48.  
  49. vector<int> H[KEY];
  50. void insert(int x) { // insert in the hash - O(1)
  51.     int line = x % KEY;
  52.     H[line].push_back(x);
  53. }
  54. bool query(int x) {
  55.     int line = x % KEY;
  56.     for (size_t i = 0; i < H[line].size(); ++i) {
  57.         if (H[line][i] == x) {
  58.             return true;
  59.         }
  60.     }
  61.     return false;
  62. }
  63.  
  64. int n, x;
  65. int m;
  66.  
  67. int main() {
  68.     cin >> n >> m; // read the number of elements in your array and the number of querys
  69.     for (int i = 0; i < n; ++i) {
  70.         cin >> x; // read your x
  71.         insert(x); // insert your number x in the hash
  72.     }
  73.     for (int i = 0; i < m; ++i) { // for each of the m querys
  74.         cin >> x;
  75.         if (query(x) == true) {
  76.             cout << "Number " << x << " is in the hash\n";
  77.         } else {
  78.             cout << "Number " << x << " is not in the hash\n";
  79.         }
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement