POJ 1654 Area(计算几何)

计算一个多边形的面积

把多边形划分成多个三角形,利用叉积计算有向面积累加即可

代码:

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

typedef long long ll;

struct Point {
    ll x, y;
    Point() {}
    Point(ll x, ll y) {
        this->x = x;
        this->y = y;
    }
};

typedef Point Vector;

ll Cross(Vector A, Vector B) {return A.x * B.y - A.y * B.x;} //叉积

Vector operator + (Vector A, Vector B) {
    return Vector(A.x + B.x, A.y + B.y);
}

Vector operator - (Vector A, Vector B) {
    return Vector(A.x - B.x, A.y - B.y);
}

//n边形的面积
ll PolygonArea(Point *p, int n) {
    double area = 0;
    for (int i = 1; i < n - 1; i++)
        area += Cross(p[i] - p[0], p[i + 1] - p[0]);
    if (area < 0) area = -area;
    return area;
}

const int N = 1000005;
const int d[10][2] = {0, 0, 1, -1, 1, 0, 1, 1, 0, -1, 0, 0, 0, 1, -1, -1, -1, 0, -1, 1};
Point p[2], O;
int t, n;
char str[N];

int main() {
    scanf("%d", &t);
    while (t--) {
        scanf("%s", str);
        n = 1;
        int now = 0, pre = 1;
        p[now] = Point(0, 0);
        ll ans = 0;
        O.x = 0; O.y = 0;
        while (str[n - 1]) {
            swap(pre, now);
            p[now].x = p[pre].x + d[str[n - 1] - '0'][0];
            p[now].y = p[pre].y + d[str[n - 1] - '0'][1];
            n++;
            if (n == 1) continue;
            ans += Cross(p[pre] - O, p[now] - O);
        }
        if (ans < 0) ans = -ans;
        if (ans % 2) printf("%lld.5\n", ans / 2);
        else printf("%lld\n", ans / 2);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值