nyoj 1101 So Easy[II]:点击打开链接
hdu 2036 改革春风吹满地:点击打开链接
求多边形的面积的方法,就是利用叉积的几何意义:以两向量为邻边的平行四边形的有向面积。
nyoj 这道题是按顺时针给出的点。而hdu上的按逆时针的顺序给出的。其实无所谓,最后求出的面积都是正的。
code:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 1e2 + 4;
struct Point{
double x, y;
}p[N];
struct Vector{
double x, y;
};
double operator *(Vector a, Vector b){
return a.x * b.y - b.x * a.y;
}
int n;
double f(){
double sum = 0;
Vector a, b;
for(int i = 1; i < n - 1; i ++){
a.x = p[i].x - p[0].x; a.y = p[i].y - p[0].y;
b.x = p[i + 1].x - p[0].x; b.y = p[i + 1].y - p[0].y;
sum += (a * b) * 0.5;
}
return sum;
}
int main(){
while(~scanf("%d",&n)){
for(int i = 0; i < n; i ++){
scanf("%lf %lf", &p[i].x, &p[i].y);
}
double ans = f();
printf("%.2lf\n", fabs(ans));
}
return 0;
}
计算几何要多积累一些模板。