POJ - 3348 Cows (凸包+凸多边形面积)

链接:Cows - POJ 3348 - Virtual Judge

题意:给出n个点。求把这n个点围起来的凸多边形的面积,然后除以50。

思路:凸包裸题,凸包不严格的说就是把所有点围起来的凸多边形。怎么求呢?按最左下的点进行极角排序,然后把凸包中的点放进栈中。每次要放点时,判断一下是不是向左转,若向右转则把栈顶出栈。注意判断向左时,重合的情况。

#include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 1e4+10;
const double eps = 1e-8;
int sgn(double x)
{
	if(fabs(x)<eps) return 0;
	else if(x<0) return -1;
	else return 1;
}
struct Point
{
	int x,y;
	Point(){}
	Point(int x,int y):x(x),y(y){}
	Point operator -(const Point& b)const//相减 
	{
		return Point(x-b.x,y-b.y);
	}
	int operator ^(const Point& b)const//叉乘 
	{
		return x*b.y-y*b.x;
	}
}ps[N],st[N];
int n,pos,top;
double x;

bool cmp(const Point& a,const Point& b)
{
	x=(a-ps[1])^(b-ps[1]);
	if(x==0)
	{
		if(a.y==b.y)
			return a.x<b.x;
		else return a.y<b.y;
	}
	else if(x>0) return 1;
	else return 0;
}
int dis(Point a,Point b)
{
    return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}
bool cmp1(const Point& a,const Point& b){
	return dis(a,ps[1])>dis(b,ps[1]);
}

bool check(Point a,Point b,Point c)
{
	x=(b-a)^(c-a);
	return x<=0;
}
double area()
{
	++top;
	if(top<3) return 0;
	int  ans=st[0].y*(st[top-1].x-st[1].x);
	for(int i=1;i<top;i++)
	{
		ans+=st[i].y*(st[i-1].x-st[(i+1)%top].x);
	}
	return abs(ans/100);
}
int main(void)
{
	while(~scanf("%d",&n))
	{	
		pos=1;		
		for(int i=1;i<=n;i++)
		{
			scanf("%d%d",&ps[i].x,&ps[i].y);
			if(ps[i].y<ps[pos].y || (ps[i].y==ps[pos].y&&ps[i].x<ps[pos].x))
				pos=i;
		}
		if(n<3)
		{
			puts("0");
			continue;
		}
		swap(ps[1],ps[pos]);
		sort(ps+2,ps+n+1,cmp);
    	int r=n-1;
		while(r>1&&((ps[r]-ps[1])^(ps[n]-ps[1]))==0)
			r--;
		sort(ps+r+1,ps+n+1,cmp1);
		
		top=-1;
		st[++top]=ps[1];
		st[++top]=ps[2];
		for(int i=3;i<=n;i++)
		{
			while(top>1&&check(st[top-1],st[top],ps[i])) 
				top--;			
			st[++top]=ps[i];
		}
		printf("%d\n",(int)area());	
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值