smatskevich

ConvexHull

Apr 23rd, 2022 (edited)
961
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. #include <cmath>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. struct Point {
  8.   double x;
  9.   double y;
  10. };
  11.  
  12. struct Vector {
  13.   double x;
  14.   double y;
  15.  
  16.   double Len() const;
  17. };
  18.  
  19. Point operator+(const Point& p, const Vector& v) {
  20.   return {p.x + v.x, p.y + v.y};
  21. }
  22.  
  23. Vector operator+(const Vector& v1, const Vector& v2) {
  24.   return {v1.x + v2.x, v1.y + v2.y};
  25. }
  26.  
  27. Vector operator-(const Vector& v1, const Vector& v2) {
  28.   return {v1.x - v2.x, v1.y - v2.y};
  29. }
  30.  
  31. Vector operator-(const Point& p1, const Point& p2) {
  32.   return {p1.x - p2.x, p1.y - p2.y};
  33. }
  34.  
  35. double DotProduct(const Vector& v1, const Vector& v2) {
  36.   return v1.x * v2.x + v1.y * v2.y;
  37. }
  38.  
  39. double CrossProduct(const Vector& v1, const Vector& v2) {
  40.   return v1.x * v2.y - v1.y * v2.x;
  41. }
  42.  
  43. double Vector::Len() const {
  44.   return sqrt(x * x + y * y);
  45. }
  46.  
  47. bool operator==(const Point& p1, const Point& p2) {
  48.   return p1.x == p2.x && p1.y == p2.y;
  49. }
  50.  
  51. bool operator!=(const Point& p1, const Point& p2) {
  52.   return !operator==(p1, p2);
  53. }
  54.  
  55. istream& operator>>(istream& in, Vector& v) {
  56.   in >> v.x >> v.y;
  57.   return in;
  58. }
  59.  
  60. istream& operator>>(istream& in, Point& v) {
  61.   in >> v.x >> v.y;
  62.   return in;
  63. }
  64.  
  65. vector<Point> ConvexHull(vector<Point>& p) {
  66.   if (p.empty()) return {};
  67.   auto it = min_element(p.begin(), p.end(), [](const Point& p1, const Point& p2) -> bool {
  68.     return p1.y < p2.y || (p1.y == p2.y && p1.x < p2.x);
  69.   });
  70.  
  71.   vector<Point> ch;
  72.   ch.push_back(*it);
  73.  
  74.   for (;;) {
  75.     Point cur = ch.back();
  76.     Point cand = p.front();
  77.     for (int i = 1; i < p.size(); ++i) {
  78.       double cross = CrossProduct(cand - cur, p[i] - cur);
  79.       if (cross < -eps || (cross < eps && (p[i] - cur).Len() > (cand - cur).Len())) cand = p[i];
  80.     }
  81.     if (cand == ch.front()) return ch;
  82.     ch.push_back(cand);
  83.   }
  84. }
  85.  
  86. int main() {
  87.   ios::sync_with_stdio(false);
  88.   cin.tie(nullptr);
  89.  
  90.   int n = 0; cin >> n;
  91.   vector<Point> p(n);
  92.   for (int i = 0; i < n; ++i) cin >> p[i];
  93.   vector<Point> ch = ConvexHull(p);
  94.   for (const auto& point : ch) {
  95.     cout << point.x << " " << point.y << "\n";
  96.   }
  97.   return 0;
  98. }
  99.  
Add Comment
Please, Sign In to add comment