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