BSOJ1478:多边形面积 凸包

3 篇文章 0 订阅
1 篇文章 0 订阅
1478 -- 【模拟试题】多边形面积
Description
  在直角坐标系中,给出n个顶点的坐标,求这n个点所围成的图形的周长和面积。
  注意:
    (1)如果所有点共线则周长按直线的长度计算,面积视为0;
    (2)如果部分点共线按共线后的多边形计算;
    (3)所给出的n个顶点如果能围成多边形则均为凸多边形。 
Input
  第一行输入多边形顶点个数n(3 <= n <= 100);
  接下来n行每行输入一个顶点坐标x,y,x,y均为整数且坐标的绝对值均不超过100。
Output
  两行,即多边形的周长和面积(均保留两位小数)。
Sample Input
  4
  0 0
  1 0
  0 1
  1 1
Sample Output
  4.00
  1.00
Source

xinyue


求一个凸包,再用有向梯形算凸包面积,边长直接暴力计算再累加~

注意判断是不是一条直线

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
struct point
{
	double x,y;
}w[10005];
int n;
int stk[10005]={0},top=0;
point low;
bool str=1;
double X1,X2,Y1,Y2;
bool cmpp(point a,point b)
{
	if(a.y==b.y)return a.x<b.x;
	return a.y<b.y;
}
void init()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%lf%lf",&w[i].x,&w[i].y);	
	sort(w+1,w+n+1,cmpp);
	low=w[1];
	X1=w[1].x,X2=w[n].x;
	Y1=w[1].y,Y2=w[n].y;
}
double cross(point a,point b,point c)
{
	double k=(a.x-c.x)*(b.y-c.y)-(b.x-c.x)*(a.y-c.y);
	return k;
}
double squ(double x)
{
	return x*x;
}
bool cmp(point a,point b)
{
	 double judge=cross(a,b,low);
	 if(judge>0){str=0;return 1;}
	 if(judge==0&&squ(a.x-low.x)+squ(a.y-low.y)<squ(b.x-low.x)+squ(b.y-low.y))return 1;
     if(judge<0){str=0;return 0;}
	 return 0;
}
void Graham_Scan()
{
    top=2;
	stk[1]=1;
	stk[2]=2;
	w[n+1]=low;
	for(int i=3;i<=n+1;i++)
	{
		while(top>1&&cross(w[stk[top]],w[i],w[stk[top-1]])<=0)top--;
		stk[++top]=i;
	}	
}
double area=0;
double len=0;
void cal()
{
	if(str==1)
	{
		len=sqrt(squ(X1-X2)+squ(Y1-Y2));
		area=0;
		printf("%0.2lf\n%0.2lf",len,area/2);
		return;
	}
	for(int i=1;i<top;i++)//是1-->top-1,不是1-->top否则加错..
	{
		int x1=w[stk[i]].x,x2=w[stk[i+1]].x;
		int y1=w[stk[i]].y,y2=w[stk[i+1]].y;
		area+=(((y1+y2)*(x1-x2)));
		len+=sqrt(squ(x1-x2)+squ(y1-y2));
	}
	printf("%0.2lf\n%0.2lf",len,area/2);
}
int main(){
	init();
	sort(w+2,w+n+1,cmp);//从y最小,最左边的点开始,所以按照极角序排序时不用管它
	Graham_Scan();
	cal();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值