HDU 2202 最大三角形

本文介绍了一个用于求解凸包上的最大三角形面积的算法,详细解释了元算法背后的数学原理,包括向量积的概念和如何利用排序和凸包特性来优化计算过程。

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

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=50005;

struct node{
    int x,y;
}e[maxn],res[maxn];

int cmp(node a,node b)
{
    if(a.x==b.x)return a.y<b.y;
    return a.x<b.x;
}

int cross(node a,node b,node c)
{
    return (a.x-c.x)*(b.y-c.y)-(b.x-c.x)*(a.y-c.y);
}

int convex(int n)
{
    int top = -1;
    res[++top] = e[0];
    res[++top] = e[1];
    for(int i=2;i<n;i++)
    {
        while(top && cross(res[top],e[i],res[top-1])<=0)
            top--;
        res[++top] = e[i];
    }
    int midtop = top;
    for(int i=n-2;i>=0;i--)
    {
        while(top>midtop && cross(res[top],e[i],res[top-1])<=0)
        {
            top--;
        }
        res[++top] =e[i];
    }
    return top;
}

int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        int i,j,k,x,y,m;
        for(i=0;i<n;i++)
            scanf("%d%d",&e[i].x,&e[i].y);
        sort(e,e+n,cmp);
        m=convex(n);
        int ans=0;
        for(i=0;i<m;i++)
            for(j=i+1;j<m;j++)
                for(k=j+1;k<m;k++)
                ans=max(ans,cross(res[j],res[k],res[i]));
        printf("%.2lf\n",0.5*ans);
    }
    return 0;
}
/*
    水平序的Andrew算法,求凸包。时间复杂度O(n)
    最大三角形的三个顶点必定在凸包上,枚举即可。

    向量积:a×b=x1*y2-x2*y1;当a×b>0时b在a的逆时针方向,a×b<0时b在顺时针方向,a×b=0时共线
    |a×b|=|a|*|b|*sin<a,b>,可以求三角形面积。

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值