ConvexHull.cc 2.0 KB

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