Advertisement
asdfg0998

dadasd

Sep 15th, 2024
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <vector>
  4. #include <unordered_map>
  5. #include <cmath>
  6. using namespace std;
  7.  
  8. #include <unordered_map>
  9. #include <vector>
  10. #include <cmath>
  11. #include <functional> // For custom hash function
  12. using namespace std;
  13.  
  14. // Custom hash function for pair<int, int>
  15. struct pair_hash {
  16.     template <class T1, class T2>
  17.     size_t operator()(const pair<T1, T2>& p) const {
  18.         auto h1 = hash<T1>{}(p.first);
  19.         auto h2 = hash<T2>{}(p.second);
  20.         return h1 ^ h2;  // Combine the two hashes
  21.     }
  22. };
  23.  
  24. // Helper function to compute the bucket key based on center coordinates
  25. pair<int, int> getBucket(int x, int y) {
  26.     return {x / 2, y / 2};  // Each bucket represents a 2x2 area
  27. }
  28.  
  29. int countCollidingPairs(vector<vector<int>>& centers) {
  30.     unordered_map<pair<int, int>, vector<pair<int, int>>, pair_hash> buckets;
  31.     int count = 0;
  32.    
  33.     for (const auto& center : centers) {
  34.         int x = center[0], y = center[1];
  35.         auto bucket = getBucket(x, y);
  36.  
  37.         // Check the current bucket and all neighboring buckets
  38.         for (int dx = -1; dx <= 1; ++dx) {
  39.             for (int dy = -1; dy <= 1; ++dy) {
  40.                 auto neighborBucket = make_pair(bucket.first + dx, bucket.second + dy);
  41.                 if (buckets.find(neighborBucket) != buckets.end()) {
  42.                     for (const auto& other : buckets[neighborBucket]) {
  43.                         // Check if the distance between the centers is <= 2
  44.                         if (abs(other.first - x) <= 2 && abs(other.second - y) <= 2) {
  45.                             ++count;
  46.                         }
  47.                     }
  48.                 }
  49.             }
  50.         }
  51.  
  52.         // Add the current object to its bucket
  53.         buckets[bucket].emplace_back(x, y);
  54.     }
  55.    
  56.     return count;
  57. }
  58.  
  59. int main() {
  60.     vector<vector<int>> centers = {
  61.         {1, 1}, {100000, 100000}, {99998, 99998},{100000,99996}
  62.     };
  63.     int result = countCollidingPairs(centers);
  64.     cout << "Number of colliding pairs: " << result << endl;
  65.  
  66.     return 0;
  67. }
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement