-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConvex Hull.cpp
74 lines (59 loc) · 1.75 KB
/
Convex Hull.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/// say Alhamdulillah
#include <bits/stdc++.h>
using namespace std;
#define fast \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
#define ll long long
struct Point {
ll x, y;
public:
Point() {}
Point(ll _x, ll _y) : x(_x), y(_y) {}
Point operator-(const Point &p) const { return Point(x - p.x, y - p.y); }
ll operator*(const Point &p) const { return (x * p.y - y * p.x); }
ll cross(const Point &b, const Point &c) const {
return (b - *this) * (c - *this);
}
};
bool compare(const Point &a, const Point &b) {
return (a.x < b.x) || (a.x == b.x && a.y < b.y);
}
bool cwDirectionCheck(const Point &a, const Point &b, const Point &c) {
return (a.cross(b, c) < 0);
}
int main() {
fast;
ll i, n;
cin >> n;
vector<Point> points(n);
for (i = 0; i < n; i++) {
cin >> points[i].x >> points[i].y;
}
sort(points.begin(), points.end(), compare);
vector<Point> hull;
for (i = 0; i < n; i++) {
while (hull.size() > 1 &&
cwDirectionCheck(hull[hull.size() - 2], hull[hull.size() - 1],
points[i])) {
hull.pop_back();
}
hull.emplace_back(points[i]);
}
ll half = hull.size();
for (i = n - 1; i >= 0; i--) {
while (hull.size() > half &&
cwDirectionCheck(hull[hull.size() - 2], hull[hull.size() - 1],
points[i])) {
hull.pop_back();
}
if (i)
hull.emplace_back(points[i]);
}
sort(hull.begin(), hull.end(), compare);
hull.pop_back();
cout << hull.size() << endl;
for (const auto &p : hull)
cout << p.x << " " << p.y << endl;
}