1. 程式人生 > >poj3348 求凸包面積

poj3348 求凸包面積

題意:草地上有些樹,用樹做籬笆圍一塊最大的面積來養牛,每頭牛要50平方米才能養活,問最多能養多少隻羊

凸包求面積,分解成三角形用叉積求面積。

#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

const double eps = 1e-8;

int stk[10001], top;

struct Point {
    double x, y;
} p[10001];

int dblcmp(double k) {
    if (fabs(k) < eps) return 0;
    return k > 0 ? 1 : -1;
}

double multi(Point p0, Point p1, Point p2) {
    return (p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x);
}

double getDis(Point a, Point b) {
    return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}

bool cmp(const Point& a, const Point& b) {
    int d = dblcmp(multi(p[0], a, b));
    if (!d) return getDis(p[0], a) < getDis(p[0], b);
    return d > 0;
}

int main()
{
    int n, i, k;
    double tx, ty;

    while (scanf ("%d", &n) != EOF) {
        if (n <= 2) {
            printf ("0\n");
            continue;
        }
        tx = ty = 100000;
        for (i = 0; i < n; i++) {
            scanf ("%lf%lf", &p[i].x, &p[i].y);
            int d = dblcmp(ty-p[i].y);
            if (!d && dblcmp(tx-p[i].x) > 0) {
               k = i; tx = p[i].x;
            } else if (d > 0) {
               k = i;
               ty = p[i].y;
               tx = p[i].x;
            }
        }
        p[k].x = p[0].x;
        p[k].y = p[0].y;
        p[0].x = tx;
        p[0].y = ty;

        sort(p+1, p+n, cmp);
        stk[0] = 0;
        stk[1] = 1;
        top = 1;
        for (i = 2; i < n; i++) {
            while (top >= 1 && dblcmp(multi(p[stk[top-1]], p[i], p[stk[top]])) >= 0) top--;
            stk[++top] = i;
        }
        double area = 0;
        for (i = 1; i < top; i++)
            area += fabs(multi(p[stk[0]], p[stk[i]], p[stk[i+1]]));
        printf ("%d\n", (int)area/100);
    }
    return 0;
}