Advertisement
Guest User

Untitled

a guest
Jun 3rd, 2020
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <stack>
  5.  
  6. struct Point {
  7.     int x;
  8.     int y;
  9. };
  10.  
  11. Point start;
  12.  
  13. int distance(Point first, Point second) {
  14.     return (first.x - second.x) * (first.x - second.x) +
  15.            (first.y - second.y) * (first.y - second.y);
  16. }
  17.  
  18. int orientation(Point around, Point first, Point second) {
  19.     int value = (first.y - around.y) * (second.x - first.x) -
  20.                 (first.x - around.x) * (second.y - first.y);
  21.     if (value == 0) return 0;
  22.     return (value > 0) ? 1 : 2;  
  23. }
  24.  
  25. bool compare(const Point first, const Point second) {
  26.     int o = orientation(start, first, second);
  27.     if (o == 0) {
  28.         return (distance(start, second) >= distance(start, first)) ? 1 : 0;
  29.     }
  30.     return (o == 2) ? 1 : 0;
  31. }
  32.  
  33. Point nextToTop(std::stack<Point>& S) {
  34.     Point temp = S.top();
  35.     S.pop();
  36.     Point result = S.top();
  37.     S.push(temp);
  38.     return result;
  39. }
  40.  
  41. std::stack<Point> convexHull(std::vector<Point> points) {
  42.     int y_min = points[0].y;
  43.     int min = 0;
  44.     for (int i = 1; i < points.size(); i++) {
  45.         if ((points[i].y < y_min) || (y_min == points[i].y && points[i].x < points[min].x)) {
  46.             y_min = points[i].y;
  47.             min = i;
  48.         }
  49.     }
  50.     std::swap(points[0], points[min]);
  51.     start = points[0];
  52.     std::sort(points.begin() + 1, points.end(),
  53.               [](auto first_point, auto second_point) {
  54.                    return compare(first_point, second_point);
  55.               });
  56.     std::stack<Point> S;
  57.     S.push(points[0]);
  58.     S.push(points[1]);
  59.     S.push(points[2]);
  60.     for (int i = 3; i < points.size(); i++) {
  61.         while (orientation(nextToTop(S), S.top(), points[i]) != 2) {
  62.             S.pop();
  63.         }
  64.         S.push(points[i]);
  65.     }
  66.     return S;
  67. }
  68.  
  69. int main() {
  70.     std::vector<Point> p = { { 0, 3 }, { 1, 1 }, { 2, 2 }, { 4, 4 }, { 0, 0 },
  71.             { 1, 2 }, { 3, 1 }, { 3, 3 } };
  72.     auto S = convexHull(p);
  73.     while (!S.empty()) {
  74.         Point p = S.top();
  75.         std::cout << p.x << ' ' << p.y << '\n';
  76.         S.pop();
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement