HDU2036 用叉乘求多边形面积
Input
输入数据包含多个测试实例,每个测试实例占一行,每行的开始是一个整数n(3<=n<=100),它表示多边形的边数(当然也是顶点数),然后是按照逆时针顺序给出的n个顶点的坐标(x1, y1, x2, y2... xn, yn),为了简化问题,这里的所有坐标都用整数表示。
输入数据中所有的整数都在32位整数范围内,n=0表示数据的结束,不做处理。
Output
对于每个测试实例,请输出对应的多边形面积,结果精确到小数点后一位小数。
每个实例的输出占一行。
Sample Input
3 0 0 1 0 0 1
4 1 0 0 1 -1 0 0 -1 0
Sample Output
0.5
2.0
/* 把矩形分解成n-2个三角形
用叉乘计算三角形面积带绝对值
但是如果在计算多变型的面积时,就不带绝对值
因为多边形分凹凸的情况,凸的贡献为正,凹的贡献为负 */
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long LL;
struct node{
int x, y;
};
struct node a[100+7];
int main()
{
int n;
while(scanf("%d", &n), n)
{
for(int i=0; i<n; i++)
{
scanf("%d %d", &a[i].x, &a[i].y);
}
double s = 0;
for(int i=2; i<n; i++)
{
int t1x = a[i-1].x - a[0].x;
int t1y = a[i-1].y - a[0].y;
int t2x = a[i].x - a[0].x;
int t2y = a[i].y - a[0].y;
// s = s + 1.0 * abs(t1x*t2y - t2x*t1y);
s = s + 1.0 * (t1x*t2y - t2x*t1y);
}
printf("%.1lf\n", s/2);
}
return 0;
}