[codevs 1249] 多边形的面积

这篇博客介绍了如何使用Cross叉积计算有向面积,从而求解凹多边形的面积。提供了高效的代码实现,总时间耗费仅5ms,内存耗费256kB。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题解:

模板,利用Cross叉积表示的是有向面积,同样可以求凹多边形的面积。

代码:

总时间耗费: 5ms
总内存耗费: 256 kB

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

const int maxn = 100 + 10;
int n;

struct Point {
    int x, y;
    Point(int x=0, int y=0):x(x),y(y) {}
}P[maxn];

typedef Point Vector;

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); }
Vector operator * (Vector A, int p) { return Vector(A.x*p, A.y*p); }
Vector operator / (Vector A, int p) { return Vector(A.x/p, A.y/p); }

bool operator < (const Vector& a, const Vector& b) {
    return a.x < b.x || (a.x == b.x && a.y < b.y);
}

int Dot(Vector A, Vector B) { return A.x*B.x + A.y*B.y; }
int Length(Vector A) { return sqrt(Dot(A, A)); }
int Angle(Vector A, Vector B) { return acos(Dot(A, B) / Length(A) / Length(B)); }
int Cross(Vector A, Vector B) { return A.x*B.y - A.y*B.x; }
int Area2(Point A, Point B, Point C) { return Cross(B-A, C-A); }

int PolygonArea() {
    int area = 0;
    for(int i = 1; i < n-1; i++) 
        area += Cross(P[i]-P[0], P[i+1]-P[0]);
    return area/2;
}

int main() {
    scanf("%d", &n);
    for(int i = 0; i < n; i++) 
        scanf("%d%d", &P[i].x, &P[i].y);

    printf("%d\n", PolygonArea());
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值