刚写了一个凸包 graham 算法,mark一下。
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
struct Point{
int x,y,xx,yy;
Point(int a,int b)
{
x=a,y=b;
}
void set(int a,int b)
{
xx=a,yy=b;
}
};
bool cmp(Point *point1,Point* point2)
{
return ((point1->xx-point1->x)*(point1->yy-point2->y)-(point1->xx-point2->x)*(point1->yy-point1->y))>0;
}
bool cross(Point *point1,Point* point,Point* point2)
{
//如果是左拐
if(((point->x-point1->x)*(point2->y-point->y)-(point2->x-point->x)*(point->y-point1->y))>0)
return true;
//如果是在同一直线上
else if(((point->x-point1->x)*(point2->y-point->y)-(point2->x-point->x)*(point->y-point1->y))==0&&(point->x>point2->x||point->y>point2->y))
return true;
return false;
}
int main()
{
int n,x,y,i;
cin>>n;
vector<Point*> nums;
Point* point,*tmp,*tmp1,*tmp2;
for(i=0;i<n;++i)
{
cin>>x>>y;
//nums[i]=new Point(x,y);
//找到第一个凸包点
if(!i)
point=new Point(x,y);
else
{
if((point->y>y)||(point->y==y&&point->x>x))
{
tmp=new Point(point->x,point->y);
nums.push_back(tmp);
//
point->x=x;
point->y=y;
}
else
{
tmp=new Point(x,y);
nums.push_back(tmp);
}
}
}
//
for(i=0;i<n-1;++i)
{
nums[i]->set(point->x,point->y);
}
//对剩下的n-1个点排序
sort(nums.begin(),nums.end(),cmp);
//求凸包上的点
stack<Point*> st;
st.push(point);
st.push(nums[0]);
st.push(nums[1]);
for(i=2;i<n-1;++i)
{
tmp1=st.top();
st.pop();
tmp2=st.top();
while(!cross(tmp2,tmp1,nums[i])){
tmp1=tmp2;
st.pop();
tmp2=st.top();
}
st.push(tmp1);
st.push(nums[i]);
}
cout<<"==============="<<endl;
while(!st.empty())
{
cout<<st.top()->x<<","<<st.top()->y<<endl;
st.pop();
}
system("pause");
return 0;
}