【计算凸包面积】 POJ 3348

银月城传送门

【题目大意】给你n个点,求它们围出来的凸包的面积除以50【向下取整】

大概是道模板题。具体有些细节需要注意,见代码。

#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
struct point{
	int x,y;
	point(int a=0,int b=0){x=a,y=b;}
	friend inline point operator -(const point &lhs,const point &rhs){
		return point(lhs.x-rhs.x,lhs.y-rhs.y);
	}
	friend inline point operator +(const point &lhs,const point &rhs){
		return point(lhs.x+rhs.x,lhs.y+rhs.y);
	}
	friend inline int operator *(const point &lhs,const point &rhs){
		return lhs.x*rhs.y-lhs.y*rhs.x;
	}
	friend inline int dot(const point &lhs,const point &rhs){
		return lhs.x*rhs.x+lhs.y*rhs.y;
	}
}a[100005],st[100005];
int top=0,id=0,n;

//用叉积判方向。
bool cmp(point p1,point p2){
	int K=point(p1.x-a[0].x,p1.y-a[0].y)*point(p2.x-a[0].x,p2.y-a[0].y);
	if(K==0) return ((p1.y-a[0].y)*(p1.y-a[0].y)+(p1.x-a[0].x)*(p1.x-a[0].x))<=((p2.y-a[0].y)*(p2.y-a[0].y)+(p2.x-a[0].x)*(p2.x-a[0].x));
	return K>0;
}
int main(){
	scanf("%d",&n);
	for(int i=0;i<n;++i){
		scanf("%d%d",&a[i].x,&a[i].y);
		if(a[i].x<a[id].x){id=i;}
		else if(a[i].x==a[id].x&&a[i].y<a[id].y) id=i;
	}

    //特判一下。
	if(n<=2){
		putchar('0');
		putchar('\n');
		return 0;
	}
	swap(a[0],a[id]);
	sort(a+1,a+n,cmp);
	st[++top]=a[0];
    
    //注意for循环的初始值和终止值。
	for(int i=1;i<n;++i){
		point now=a[i];
		while(top>=3&&((st[top]-st[top-1])*(now-st[top-1])<=0)) top--;
		st[++top]=now;
	}
    
	double area=0;
	st[top+1]=st[1];//这里注意一下!
	for(int i=1;i<=top;++i)
		area+=st[i]*st[i+1];
    //面积是area除以2!
    //这道题还要除以一个50,一起除掉就是100.
	printf("%d\n",int(area/100));
}

猜你喜欢

转载自blog.csdn.net/g21wcr/article/details/83065449
今日推荐