Advertisement
Jasir

Convex Hull

Sep 8th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. struct point{
  2.     int x, y;
  3. };
  4.  
  5. point P[mx], C[mx], P0;
  6.  
  7. int triArea(point a, point b, point c) {
  8.     return (a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y));
  9. }
  10.  
  11. int sqDist(point a, point b) {
  12.     return ((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
  13. }
  14.  
  15. int cross(point a, point b, point c) {
  16.    return ((b.x-a.x)*(c.x-b.x) + (b.y-a.y)*(c.y-b.y));
  17. }
  18.  
  19. bool comp(point a, point b) {
  20.     int d = triArea(P0, a, b);
  21.     if(d < 0) return false;
  22.     if(!d && sqDist(P0, a) > sqDist(P0, b)) return false;
  23.     return true;
  24. }
  25.  
  26. inline bool normal(point a, point b) {
  27.     return ((a.x==b.x) ? a.y < b.y : a.x < b.x);
  28. }
  29.  
  30. bool issame(point a, point b) {
  31.     return (a.x == b.x && a.y == b.y);
  32. }
  33.  
  34. int makeUnique(int np) {
  35.     sort(&P[0], &P[np], normal);
  36.     np = unique(&P[0], &P[np], issame) - P;
  37.     return np;
  38. }
  39.  
  40. int convexHull(int np) {
  41.     if(np<=2) {
  42.         for(int i=0;i<np;i++){
  43.             C[i] = P[i];
  44.         }
  45.         return np;
  46.     }
  47.  
  48.     int i, j, nc, pos = 0;
  49.     for(i = 1; i < np; i++)
  50.         if(P[i].y<P[pos].y || (P[i].y==P[pos].y && P[i].x<P[pos].x))
  51.             pos = i;
  52.     swap(P[0], P[pos]);
  53.     P0 = P[0];
  54.     sort(&P[1], &P[np], comp);
  55.     for(i = 0; i < 3; i++) C[i] = P[i];
  56.     for(i = j = 3; i < np; i++) {
  57.         while(triArea(C[j-2], C[j-1], P[i]) < 0) j--;
  58.         C[j++] = P[i];
  59.     }
  60.     return nc = j;
  61. }
  62.  
  63. int compress(int nc) {
  64.     int i, j, d;
  65.     C[nc] = C[0];
  66.     for(i=j=1; i < nc; i++) {
  67.         d = triArea2(C[j-1], C[i], C[i+1]);
  68.         if(d || (!d && issame(C[j-1], C[i+1]))) C[j++] = C[i];
  69.     }
  70.     return nc = j;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement