【计算n边形面积】zoj 1010 Area

本文详细介绍了如何通过冒泡思想判断多边形边是否相交,并结合叉乘法计算多边形面积,确保每组数据间的清晰区分。重点在于解决有序点给出的多边形中线段相交问题,最终通过实例代码演示实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

zoj 1010 Area

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=10

问题描述:有序n个点构成的n边形面积

【无序n边形面积】如果n个点无序,叉乘解决

【n个点依次给出的多边形面积】这时候要考虑多边形边相交的问题,首先利用冒泡的思想O(n^2)判断是否有线段相交,满足之后叉乘求出面积即可。

思路

计算多边形的面积+线段相交判定

注意2点,每组数据空一行;面积area保留两位小数!!!WA了好几次QAQ


参考代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<vector>
#include<algorithm>
#include<set>
#include<sstream>
#define eps 1e-9
using namespace std;

typedef long long ll;

const int _max = 1e3 + 10;

int dcmp(double x){
  if(fabs(x)<eps) return 0;else return x < 0?-1:1;
}

struct point{
  double x,y;
}p[_max];

double cross(point a,point b){//叉乘
  return a.x*b.y - b.x*a.y;
}

int n;

bool inter(point a,point b,point c,point d)//判断线段相交
{
    if(min(a.x,b.x)>max(c.x,d.x)||
       min(a.y,b.y)>max(c.y,d.y)||
       min(c.x,d.x)>max(a.x,b.x)||
       min(c.y,d.y)>max(a.y,b.y) ) return 0;
    double h,i,j,k;
    h=(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
    i=(b.x-a.x)*(d.y-a.y)-(b.y-a.y)*(d.x-a.x);
    j=(d.x-c.x)*(a.y-c.y)-(d.y-c.y)*(a.x-c.x);
    k=(d.x-c.x)*(b.y-c.y)-(d.y-c.y)*(b.x-c.x);
    return h*i<=eps&&j*k<=eps;
}

double getarea(){//多边形面积
  double sum = 0;
  for(int i = 0; i < n; ++ i)
    sum+=cross(p[i],p[(i+1)%n]);
  return fabs(sum)/2;
}

int main(){
 #ifndef ONLINE_JUDGE
 freopen("input.txt","r",stdin);
 #endif // ONLINE_JUDGE
 int cnt = 1;
 while(scanf("%d",&n) == 1&& n){
    for(int i = 0; i < n; ++ i)
        scanf("%lf%lf",&p[i].x,&p[i].y);
    if(cnt > 1) printf("\n");//每组数据空一行哎!!!!
    printf("Figure %d: ",cnt++);
    bool ok =true;
    for(int i = 0; i < n&&ok; ++ i)
        for(int j = i + 2; j + 1 < n &&ok; ++ j)
        if(inter(p[i],p[(i+1)%n],p[j],p[(j+1)% n])) {//点是有序给出的,要判断线段相交
           ok = false;
        }
    if(!ok) {puts("Impossible");continue;}
    double tar = getarea();
    if(dcmp(tar) == 0) puts("Impossible");
    else printf("%.2f\n",tar);
 }
 return 0;
}
  • 加粗 Ctrl + B
  • 斜体 Ctrl + I
  • 引用 Ctrl + Q
  • 插入链接 Ctrl + L
  • 插入代码 Ctrl + K
  • 插入图片 Ctrl + G
  • 提升标题 Ctrl + H
  • 有序列表 Ctrl + O
  • 无序列表 Ctrl + U
  • 横线 Ctrl + R
  • 撤销 Ctrl + Z
  • 重做 Ctrl + Y
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值