-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvex_hull.cpp
More file actions
58 lines (43 loc) · 1.37 KB
/
Copy pathconvex_hull.cpp
File metadata and controls
58 lines (43 loc) · 1.37 KB
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
/*
-> Convex Hull
-> https://usaco.guide/plat/convex-hull
-> tested on https://open.kattis.com/problems/convexhull
*/
using coord = int;
struct Point {
coord x, y;
int id;
};
bool comp(const Point &a, const Point &b) {
return make_tuple(a.y, a.x, a.id) < make_tuple(b.y, b.x, b.id);
}
coord cross(const Point &O, const Point &A, const Point &B) {
return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);
}
bool comp2(Point a, Point b) {
return make_tuple(a.x, a.y) == make_tuple(b.x, b.y);
}
// Returns a list of points on the convex hull in counter-clockwise order.
// Note: the last point in the returned list is the same as the first one.
vector<Point> convexHull(vector<Point> P) {
// Sort points lexicographically
sort(P.begin(), P.end(), comp);
P.resize(distance(P.begin(), unique(all(P), comp2)));
int n = P.size(), k = 0;
if (n == 1) return P;
vector<Point> H(2 * n);
// Build lower hull
for (int i = 0; i < n; ++i) {
while (k >= 2 && cross(H[k - 2], H[k - 1], P[i]) <= 0)
k--;
H[k++] = P[i];
}
// Build upper hull
for (int i = n - 1, t = k + 1; i > 0; --i) {
while (k >= t && cross(H[k - 2], H[k - 1], P[i - 1]) <= 0)
k--;
H[k++] = P[i - 1];
}
H.resize(k - 1);
return H;
}