Advertisement
LinKin

Convex Hull

Nov 17th, 2011
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. /*
  2.     Algorithm: Convex Hull( Graham Scan )
  3.     Compexity: O( nlogn )
  4. */
  5.  
  6. #include<stdio.h>
  7. #include<string.h>
  8. #include<vector>
  9. #include<algorithm>
  10. using namespace std;
  11.  
  12. struct POINT{
  13.     long x,y;
  14.     long I;
  15.     POINT( long x = 0,long y = 0,long I = 0 )
  16.     {
  17.         this->x = x;
  18.         this->y = y;
  19.         this->I = I;
  20.     }
  21. };
  22. bool operator<( const POINT &a,const POINT &b )
  23. {
  24.     if( a.x != b.x ) return a.x < b.x;
  25.     else return a.y < b.y;
  26. }
  27.  
  28. long N;
  29. vector<POINT> Pt;
  30. vector<bool> Del;
  31.  
  32. long Area2( POINT a,POINT b,POINT c )
  33. {
  34.     return a.x*b.y - a.y*b.x + a.y*c.x - a.x*c.y + b.x*c.y - c.x*b.y;
  35. }
  36.  
  37. bool Cmp( const POINT &a,const POINT &b )
  38. {
  39.     long Ar = Area2( Pt[0],a,b );
  40.     if( Ar ) return Ar>0;
  41.     long Dx = labs( Pt[0].x-a.x ) - labs( Pt[0].x-b.x );
  42.     long Dy = labs( Pt[0].y-a.y ) - labs( Pt[0].y-b.y );
  43.     if( Dx<0 || Dy<0 ){
  44.         Del[a.I] = true;
  45.         return true;
  46.     }
  47.     else if( Dx>0 || Dy>0 ){
  48.         Del[b.I] = true;
  49.         return false;
  50.     }
  51.     return true;
  52. }
  53. /* to del all linear point */
  54. void Squash( void )
  55. {
  56.     long i,j;
  57.     for( i=j=0;i<N;i++){
  58.         if( Del[Pt[i].I] ) continue;
  59.         Pt[j] = Pt[i];
  60.         j++;
  61.     }
  62.     Pt.resize( j );
  63.     N = j;
  64. }
  65. void ConvexHull( vector<POINT> &Hull )
  66. {
  67.     sort( Pt.begin(),Pt.end()); // Pt[0] wiil contain leftmst-lowest point
  68.     sort( Pt.begin()+1,Pt.end(),Cmp );
  69.     Squash();
  70.     if( Pt.size()>=1 ) Hull.push_back( Pt[0] );
  71.     if( Pt.size()>=2 ) Hull.push_back( Pt[1] );
  72.     long i = 2;
  73.     while( i<N ){
  74.         long s = Hull.size();
  75.         if( Area2( Hull[s-2],Hull[s-1],Pt[i] )>0 ){
  76.             Hull.push_back( Pt[i] );
  77.             i++;
  78.         }
  79.         else Hull.pop_back();
  80.     }
  81. }
  82.  
  83. int main( void )
  84. {
  85.     //freopen("text1.txt","r",stdin );
  86.     Pt.resize(N); // repeated point is needed to omit by set
  87.     Del.resize(N);
  88.     vector<POINT> Hull;
  89.     ConvexHull( Hull );
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement