1. 程式人生 > >凸包(轉自水神百度文庫)

凸包(轉自水神百度文庫)

#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
struct Point
{
    double x,y,len;
}Pt[20000],Stack[20000],Point_A;
double Cross(Point a,Point b,Point c)
{
    return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
}
double Dis(Point a,Point b)
{
    return sqrt(pow(a.x-b.x,2)+pow(a.y-b.y,2));
}
void FindPoint(int n)
{
    int i,tempNumber=0;
    Point tempPoint;
    Point_A=Pt[0];
    for(i=1;i<n;i++)
    {
        if(Pt[i].y<Point_A.y||Pt[i].y==Point_A.y&&Pt[i].x<Point_A.x)
        {
            tempNumber=i;
            Point_A=Pt[i];
        }
    }
    tempPoint=Pt[0];
    Pt[0]=Pt[tempNumber];
    Pt[tempNumber]=tempPoint;
}
bool Cmp(Point a,Point b)
{
    double k=Cross(Point_A,a,b);
    if(k>0) return true;
    if(k<0) return false;
    a.len=Dis(Point_A,a);
    b.len=Dis(Point_A,b);
    return a.len>b.len;
}
void Graham(int n)
{
    int i,top=2;
    Pt[n]=Pt[0];
    Stack[0]=Pt[0];
    Stack[1]=Pt[1];
    Stack[2]=Pt[2];
    for(i=3;i<=n;i++)
    {
        while(Cross(Stack[top-1],Stack[top],Pt[i])<=0&&top>1)
        top--;
        Stack[++top]=Pt[i];
    }
}
int main(void)
{
    int i,Num;
    while(scanf("%d",&Num)!=EOF)
    {
        for(i=0;i<Num;i++)
        scanf("%lf%lf",&Pt[i].x,&Pt[i].y);
        FindPoint(Num);
        sort(Pt,Pt+Num,Cmp);
        Graham(Num);
    }
    return 0;
}