凸包 graham 算法

刚写了一个凸包 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值