Guest User

Monotone chain

a guest
Jun 4th, 2020
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. // Implementation of Andrew's monotone chain 2D convex hull algorithm.
  2. // Asymptotic complexity: O(n log n).
  3. // Practical performance: 0.5-1.0 seconds for n=1000000 on a 1GHz machine.
  4. #include <algorithm>
  5. #include <vector>
  6. using namespace std;
  7.  
  8. typedef double coord_t;         // coordinate type
  9. typedef double coord2_t;  // must be big enough to hold 2*max(|coordinate|)^2
  10.  
  11. struct Point {
  12.     coord_t x, y;
  13.  
  14.     bool operator <(const Point &p) const {
  15.         return x < p.x || (x == p.x && y < p.y);
  16.     }
  17. };
  18.  
  19. // 3D cross product of OA and OB vectors, (i.e z-component of their "2D" cross product, but remember that it is not defined in "2D").
  20. // Returns a positive value, if OAB makes a counter-clockwise turn,
  21. // negative for clockwise turn, and zero if the points are collinear.
  22. coord2_t cross(const Point &O, const Point &A, const Point &B)
  23. {
  24.     return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);
  25. }
  26.  
  27. // Returns a list of points on the convex hull in counter-clockwise order.
  28. // Note: the last point in the returned list is the same as the first one.
  29. vector<Point> convex_hull(vector<Point> P)
  30. {
  31.     size_t n = P.size(), k = 0;
  32.     if (n <= 3) return P;
  33.     vector<Point> H(2*n);
  34.  
  35.     // Sort points lexicographically
  36.     sort(P.begin(), P.end());
  37.  
  38.     // Build lower hull
  39.     for (size_t i = 0; i < n; ++i) {
  40.         while (k >= 2 && cross(H[k-2], H[k-1], P[i]) <= 0) k--;
  41.         H[k++] = P[i];
  42.     }
  43.  
  44.     // Build upper hull
  45.     for (size_t i = n-1, t = k+1; i > 0; --i) {
  46.         while (k >= t && cross(H[k-2], H[k-1], P[i-1]) <= 0) k--;
  47.         H[k++] = P[i-1];
  48.     }
  49.  
  50.     H.resize(k-1);
  51.     return H;
  52. }
Add Comment
Please, Sign In to add comment