凸包模板题

http://acm.nyist.net/JudgeOnline/problemrank.php?pid=78

AC代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<cstring>
#define N 105
using namespace std;
struct Point
{
	int x;
	int y;
}p[N];
int top,n,s[N];
int dis(const Point& a,const Point& b)
{return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);}
int cross(const Point& a,const Point& b,const Point& c)
{return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);}
bool cmp(const Point& a,const Point& b)//幅角排序
{
	int ans=cross(p[0],a,b);
	if((ans>0)||(ans==0&&dis(p[0],a)>dis(p[0],b))) return true;
	return false;
}
bool cmp1(const Point& a,const Point& b)
{return (a.x<b.x||(a.x==b.x&&a.y<b.y));}
 void graham()//凸包模板
 {
	 s[0]=0;
	 s[1]=1;
	 top=1;
	 for(int i=2;i!=n;++i)
	 {
		 while(top&&cross(p[s[top-1]],p[s[top]],p[i])<0) top--;
		 s[++top]=i;
	 }
	 top++;
 }
 int main()
 {
	 int T;
	 scanf("%d",&T);
	 while(T--)
	 {
		 scanf("%d",&n);
		 for(int i=0;i!=n;++i)
			 scanf("%d%d",&p[i].x,&p[i].y);
		  Point ans=p[0];
		  int u=0;
		  for(int i=1;i!=n;++i)
			  if((ans.y>p[i].y)||(ans.y==p[i].y&&ans.x>p[i].x)) ans=p[i],u=i;
		  if(u) swap(p[u],p[0]);
		   sort(p+1,p+n,cmp);
		   memset(s,0,sizeof(s));
		   graham();
		   Point result[N];
		   for(int i=0;i!=top;++i)
			   result[i]=p[s[i]];
		   sort(result,result+top,cmp1);
		   for(int i=0;i!=top;++i)
			   cout<<result[i].x<<" "<<result[i].y<<endl;  
	 }return 0;
 }


 

你可能感兴趣的:(凸包模板题)