Advertisement
dmkozyrev

convex_hull2.cpp

Jan 16th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. struct pt {
  9.     double x, y;
  10. };
  11.  
  12. int main(){
  13.     ofstream fout("out2.txt");
  14.     ifstream fin("in.txt");
  15.     double x, y;
  16.     vector<pt> v;
  17.     while(fin>>x>>y){
  18.         pt p = {x, y};
  19.         v.push_back(p);
  20.     }
  21. //  vector<pt> v = {
  22. //      {-2,-1},
  23. //      {-1,-2},
  24. //      { 1,-2},
  25. //      { 2,-1},
  26. //      { 2, 1},
  27. //      { 1, 2},
  28. //      {-1, 2},
  29. //      {-2, 1}
  30. //  };
  31.    
  32.     void convex_hull(vector<pt> &);
  33.     convex_hull(v);
  34.     int i = 0;
  35.     int j = v.size()-1;
  36.     while (i < j)
  37.         swap(v[i++], v[j--]);
  38.    
  39.     for(auto & i : v)
  40.         fout << i.x << " " << i.y << endl;
  41. }
  42.  
  43. bool cmp (pt a, pt b) {
  44.     return a.x < b.x || a.x == b.x && a.y < b.y;
  45. }
  46.  
  47. bool cw (pt a, pt b, pt c) {
  48.     return a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y) < 0;
  49. }
  50.  
  51. bool ccw (pt a, pt b, pt c) {
  52.     return a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y) > 0;
  53. }
  54.  
  55. void convex_hull (vector<pt> & a) {
  56.     if (a.size() == 1)  return;
  57.     sort (a.begin(), a.end(), &cmp);
  58.     pt p1 = a[0],  p2 = a.back();
  59.     vector<pt> up, down;
  60.     up.push_back (p1);
  61.     down.push_back (p1);
  62.     for (size_t i=1; i<a.size(); ++i) {
  63.         if (i==a.size()-1 || cw (p1, a[i], p2)) {
  64.             while (up.size()>=2 && !cw (up[up.size()-2], up[up.size()-1], a[i]))
  65.                 up.pop_back();
  66.             up.push_back (a[i]);
  67.         }
  68.         if (i==a.size()-1 || ccw (p1, a[i], p2)) {
  69.             while (down.size()>=2 && !ccw (down[down.size()-2], down[down.size()-1], a[i]))
  70.                 down.pop_back();
  71.             down.push_back (a[i]);
  72.         }
  73.     }
  74.     a.clear();
  75.     for (size_t i=0; i<up.size(); ++i)
  76.         a.push_back (up[i]);
  77.     for (size_t i=down.size()-2; i>0; --i)
  78.         a.push_back (down[i]);
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement