ConvexHull.cc 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Compute the 2D convex hull of a set of points using the monotone chain
  2. // algorithm. Eliminate redundant points from the hull if REMOVE_REDUNDANT is
  3. // #defined.
  4. // Running time: O(n log n)
  5. // INPUT: a vector of input points, unordered.
  6. // OUTPUT: a vector of points in the convex hull, counterclockwise, starting
  7. // with bottommost/leftmost point
  8. #define REMOVE_REDUNDANT
  9. typedef double T;
  10. struct PT {
  11. T x, y;
  12. PT() {}
  13. PT(T x, T y) : x(x), y(y) {}
  14. bool operator<(const PT &rhs) const { return make_pair(y,x) < make_pair(rhs.y,rhs.x); }
  15. bool operator==(const PT &rhs) const { return make_pair(y,x) == make_pair(rhs.y,rhs.x); }
  16. };
  17. T cross(PT p, PT q) { return p.x*q.y-p.y*q.x; }
  18. T area2(PT a, PT b, PT c) { return cross(a,b) + cross(b,c) + cross(c,a); }
  19. #ifdef REMOVE_REDUNDANT
  20. bool between(const PT &a, const PT &b, const PT &c) {
  21. return (fabs(area2(a,b,c)) < EPS && (a.x-b.x)*(c.x-b.x) <= 0 && (a.y-b.y)*(c.y-b.y) <= 0);
  22. }
  23. #endif
  24. void ConvexHull(vector<PT> &pts) {
  25. sort(pts.begin(), pts.end());
  26. pts.erase(unique(pts.begin(), pts.end()), pts.end());
  27. vector<PT> up, dn;
  28. for (int i = 0; i < pts.size(); i++) {
  29. while (up.size() > 1 && area2(up[up.size()-2], up.back(), pts[i]) >= EPS) up.pop_back();
  30. while (dn.size() > 1 && area2(dn[dn.size()-2], dn.back(), pts[i]) <= -EPS) dn.pop_back();
  31. up.push_back(pts[i]);
  32. dn.push_back(pts[i]);
  33. }
  34. pts = dn;
  35. for (int i = (int) up.size() - 2; i >= 1; i--) pts.push_back(up[i]);
  36. #ifdef REMOVE_REDUNDANT
  37. if (pts.size() <= 2) return;
  38. dn.clear();
  39. dn.push_back(pts[0]);
  40. dn.push_back(pts[1]);
  41. for (int i = 2; i < pts.size(); i++) {
  42. if (between(dn[dn.size()-2], dn[dn.size()-1], pts[i])) dn.pop_back();
  43. dn.push_back(pts[i]);
  44. }
  45. if (dn.size() >= 3 && between(dn.back(), dn[0], dn[1])) {
  46. dn[0] = dn.back();
  47. dn.pop_back();
  48. }
  49. pts = dn;
  50. #endif
  51. }