凸包算法

View Code
 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std; 
 4 struct point
 5 { 
 6     int x,y; 
 7 };
 8 bool multi(point p0,point p1,point p2)
 9 { 
10     return (p1.x-p0.x)*(p2.y-p0.y)>(p2.x-p0.x)*(p1.y-p0.y); 
11 } 
12 int mysort1(point a,point b)
13 { 
14     if(a.y!=b.y) 
15         return a.y<b.y;
16     if(a.y==b.y&&a.x!=b.x) 
17         return a.x<b.x;
18 }
19 
20 int mysort2(point a,point b)
21 { 
22     if(a.x!=b.x) 
23         return a.x<b.x;
24     if(a.x==b.x&&a.y!=b.y) 
25         return a.y<b.y;
26 }
27 int main()
28 { 
29     int i,n,k,len;
30     cin>>k;
31     point p[105],res[105];
32     while(k--)
33     {
34         cin>>n;
35         for(i=0;i<n;i++)
36              cin>>p[i].x>>p[i].y;
37         if(n == 1)
38         {
39             cout<<endl;
40             cout << p[0].x    << " " << p[0].y << endl;
41             continue;
42         }
43         sort(p,p+n,mysort1);
44         res[0]=p[0];
45         res[1]=p[1];
46         int top=1;
47         for(i=2;i<n;i++) 
48         {
49             while(top&&multi(p[i],res[top],res[top-1]))
50                 top--; 
51                     res[++top]=p[i];
52         }   
53         len=top;
54          res[++top]=p[n-2];
55         for(i=n-3;i>=0;i--)
56         {
57             while(top!=len&&multi(p[i],res[top],res[top-1]))
58                 top--; 
59            res[++top]=p[i];    
60         }
61         sort(res,res+top,mysort2);
62         cout<<endl;
63         for(i=0;i<top;i++)
64             cout<<res[i].x<<" "<<res[i].y<<endl;
65     } 
66     return 0;
67 }
posted @ 2012-07-08 19:00  Wheat″  阅读(151)  评论(0)    收藏  举报