HDU 1392 Surround the Trees

本文介绍了一个使用C++实现的几何问题解决方案,重点在于计算两个点之间的距离,并通过实例演示了如何使用特定函数进行操作。讨论了算法优化及在不同情况下的应用。

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

PS: 在求解两个点的时候就是两个点的距离,在这WA了一次。

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

struct point {
    int x, y;
    point(double x=0, double y=0):x(x),y(y) {}
};
point operator - (point A, point B) {
    return point(A.x-B.x, A.y-B.y);
}

double Dist(point A, point B) {
    double x = (A.x-B.x)*(A.x-B.x);
    double y = (A.y-B.y)*(A.y-B.y);
    return sqrt(x+y);
}
point ch[maxn];
vector<point> v;
int n;

double Cross(point A, point B) {
    return A.x*B.y - A.y*B.x;
}

bool cmp(point a, point b) {
    if(a.x!=b.x) return a.x < b.x;
    else return a.y<b.y;
}
int ConvexHull() {
    int m = 0;
    for(int i = 0; i < n; i++) {
        while(m>1 && Cross(ch[m-1]-ch[m-2], v[i]-ch[m-2])<=0)
            m--;
        ch[m++] = v[i];
    }
    int k = m;
    for(int i = n-2; i >= 0; i--) {
        while(m>k && Cross(ch[m-1]-ch[m-2], v[i]-ch[m-2])<=0)
            m--;
        ch[m++] = v[i];
    }
    if(n>1) m--;
    return m;
}

int main()
{
    point t;
    while(scanf("%d", &n) && n) {
        v.clear();
        for(int i = 0; i < n; i++) {
            scanf("%d%d", &t.x, &t.y);
            v.push_back(t);
        }
        sort(v.begin(), v.end(), cmp);
        int m = ConvexHull();
        double res = 0;
        if(m==2) {
            res = Dist(ch[0], ch[1]);
            printf("%.2lf\n", res);  // res*2 WA.
            continue;
        }
        for(int i = 0; i < m-1; i++) {
            res += Dist(ch[i], ch[i+1]);
        }
        res += Dist(ch[m-1], ch[0]);
        printf("%.2lf\n", res);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值