From caaaaa38905f89326c962a02f4e57c494c655df4 Mon Sep 17 00:00:00 2001 From: Kotecha Udit Hitendra <64374551+kirito-udit@users.noreply.github.com> Date: Sat, 2 Oct 2021 20:11:17 +0530 Subject: [PATCH] Create Grahams-scan-convex-hull.cpp --- Algorithms/Grahams-scan-convex-hull.cpp | 44 +++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Algorithms/Grahams-scan-convex-hull.cpp diff --git a/Algorithms/Grahams-scan-convex-hull.cpp b/Algorithms/Grahams-scan-convex-hull.cpp new file mode 100644 index 0000000..018ef85 --- /dev/null +++ b/Algorithms/Grahams-scan-convex-hull.cpp @@ -0,0 +1,44 @@ +struct pt { + double x, y; +}; + +bool cmp(pt a, pt b) { + return a.x < b.x || (a.x == b.x && a.y < b.y); +} + +bool cw(pt a, pt b, pt c) { + return a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y) < 0; +} + +bool ccw(pt a, pt b, pt c) { + return a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y) > 0; +} + +void convex_hull(vector& a) { + if (a.size() == 1) + return; + + sort(a.begin(), a.end(), &cmp); + pt p1 = a[0], p2 = a.back(); + vector up, down; + up.push_back(p1); + down.push_back(p1); + for (int i = 1; i < (int)a.size(); i++) { + if (i == a.size() - 1 || cw(p1, a[i], p2)) { + while (up.size() >= 2 && !cw(up[up.size()-2], up[up.size()-1], a[i])) + up.pop_back(); + up.push_back(a[i]); + } + if (i == a.size() - 1 || ccw(p1, a[i], p2)) { + while(down.size() >= 2 && !ccw(down[down.size()-2], down[down.size()-1], a[i])) + down.pop_back(); + down.push_back(a[i]); + } + } + + a.clear(); + for (int i = 0; i < (int)up.size(); i++) + a.push_back(up[i]); + for (int i = down.size() - 2; i > 0; i--) + a.push_back(down[i]); +}