EOJ 1127. polygon area (Computational Geometry)

Link Title: 1127. polygon area (Computational Geometry)

The meaning of problems

Given counterclockwise order \ (n-\) polygon area coordinates points, those points enclosed.

Thinking

Selecting a point on the polygon, and two points each after enumeration, the cross product is calculated, to retain the note symbol, the area of ​​the polygon is the sum of all the results of cross-product.

For chestnut:

title

Computationally FIG polygons \ (ABCDEFGH \) area, select \ (A \) point, the area is equal to \ (\ frac {1} { 2} (\ boldsymbol {AB \ times AC} + \ boldsymbol {AC \ times AD +} \ {boldsymbol the AD \ Times the AE +} \ {boldsymbol the AE \ Times the AF} + \ {boldsymbol the AF \} + AG Times \ {boldsymbol AG \ Times the AH}) \) . Wherein \ (\ triangle ABC \) of the area is negative, the \ (\ triangle ACD \) and \ (\ triangle ADE \) area is positive, the polygon \ (ABCDE \) of the polygon area corresponding to \ ( ACDE \) area minus \ (\ triangle ABC \) area.

Code

#include <cstdio>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef double db;
const db eps = 1e-10;  
const db pi = acos(-1.0);  
const ll inf = 0x3f3f3f3f3f3f3f3f;  
const ll maxn = 100 + 10;

inline int dcmp(db x) {
    if(fabs(x) < eps) return 0;
    return x > 0? 1: -1;
}

class Point {
public:
    double x, y;
    Point(double x = 0, double y = 0) : x(x), y(y) {}
    void input() {
        scanf("%lf%lf", &x, &y);
    }
    bool operator<(const Point &a) const {
        return (!dcmp(x - a.x))? dcmp(y - a.y) < 0: x < a.x;
    }
    bool operator==(const Point &a) const {
        return dcmp(x - a.x) == 0 && dcmp(y - a.y) == 0;
    }
    db dis2(const Point a) {
        return pow(x - a.x, 2) + pow(y - a.y, 2);
    }
    db dis(const Point a) {
        return sqrt(dis2(a));
    }
    db dis2() {
        return x * x + y * y;
    }
    db dis() {
        return sqrt(dis2());
    }
    Point operator+(const Point a) {
        return Point(x + a.x, y + a.y);
    }
    Point operator-(const Point a) {
        return Point(x - a.x, y - a.y);
    }
    Point operator*(double p) {
        return Point(x * p, y * p);
    }
    Point operator/(double p) {
        return Point(x / p, y / p);
    }
    db dot(const Point a) {
        return x * a.x + y * a.y;
    }
    db cross(const Point a) {
        return x * a.y - y * a.x;
    }
};

Point p[maxn];

int n;

db area() {
    if(n < 3) return 0.0;
    db ans = 0.0;
    for(int i = 2; i < n; ++i) {
        ans += (p[i] - p[1]).cross(p[i + 1] - p[1]);
    }
    return ans * 0.5;
}

int main() {
    while(~scanf("%d", &n) && n) {
        db s = 0;
        for(int i = 1; i <= n; ++i) {
            p[i].input();
        }
        s = area();
        printf("%.1lf\n", fabs(s));
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/wulitaotao/p/11688993.html