Advertisement
Alex_tz307

Convex Hull

Jan 24th, 2021
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define int long long
  3.  
  4. using namespace std;
  5.  
  6. class point {
  7.     public:
  8.         int x, y;
  9.  
  10.         void read() {
  11.             cin >> x >> y;
  12.         }
  13.  
  14.         point operator - (const point &p) const {
  15.             return point{x - p.x, y - p.y};
  16.         }
  17.  
  18.         void operator -= (const point &p) {
  19.             x -= p.x, y -= p.y;
  20.         }
  21.  
  22.         int operator * (const point &p) const {
  23.             return x * p.y - p.x * y;
  24.         }
  25.  
  26.         int crossP(const point &A, const point &B) const {
  27.             return (A - *this) * (B - *this);
  28.         }
  29.  
  30.         bool operator < (const point &A) const {
  31.             return make_pair(x, y) < make_pair(A.x, A.y);
  32.         }
  33. };
  34.  
  35. void test_case() {
  36.     int N;
  37.     cin >> N;
  38.     vector<point> points(N);
  39.     for(point &p : points)
  40.         p.read();
  41.     sort(points.begin(), points.end());
  42.     vector<point> hull;
  43.     for(int rep = 0; rep < 2; ++rep) {
  44.         int S = hull.size();
  45.         for(const point &C : points) {
  46.             while((int)hull.size() > S + 1) {
  47.                 point A = hull.end()[-2],
  48.                       B = hull.end()[-1];
  49.                 if(A.crossP(B, C) <= 0) // B la stanga lui C sau A - B - C - coliniare
  50.                     break;
  51.                 hull.pop_back(); // daca e la dreapta lui C nu face parte din convex hull
  52.             }
  53.             hull.emplace_back(C);
  54.         }
  55.         hull.pop_back();
  56.         reverse(points.begin(), points.end());
  57.     }
  58.     cout << hull.size() << '\n';
  59.     for(const point &p : hull)
  60.         cout << p.x << ' ' << p.y << '\n';
  61. }
  62.  
  63. int32_t main() {
  64.     ios_base::sync_with_stdio(false);
  65.     cin.tie(nullptr);
  66.     cout.tie(nullptr);
  67.     int T = 1;
  68.     while(T--)
  69.         test_case();
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement