凸包模板 HDU1392

题目链接
题意: 给出一些二维的点,求将其全部包围起来所需的线段长度。
先求出凸包,再遍历每条线段求长度。
(只有两个点时,答案就是两点间的距离)

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <iomanip>
using namespace std;
const int N = 5e2 + 5;
struct Pt{
    int x, y;
    Pt() {}
    Pt(int x, int y) : x(x), y(y) {}
    friend Pt operator - (const Pt &a, const Pt &b) {
        return Pt(a.x - b.x, a.y - b.y);
    }
};
Pt t[105], res[105];

inline int det(const Pt &a, const Pt &b) {
    return a.x * b.y - a.y * b.x;
}

inline bool cmp(const Pt &a, const Pt &b) {
    int flag = det(b- t[0], a - t[0]);
    return flag < 0 || (flag == 0 && a.x < b.x);
}

int convex_hull(Pt *a, Pt *res, int n) {
    int k = 0;
    for(int i = 1; i < n; i ++)
        if(a[k].y > a[i].y || (a[k].y == a[i].y && a[k].x > a[i].x))
            k = i;
    if(k != 0)
        swap(a[0], a[k]);
    sort(a + 1, a + n, cmp);
    res[0] = a[0], res[1] = a[1];
    int m = 1;
    for(int i = 2; i < n; i ++) {
        while(m && det(res[m] - res[m - 1], a[i] - res[m -1]) <= 0)
            m --;
        res[++ m] = a[i];
    }
    return ++ m;
}

inline double norm (const Pt &p) {
    return sqrt(p.x * p.x + p.y * p.y);
}


int main() {
    ios::sync_with_stdio(false);
    int n;
    while(cin >> n, n) {
        for(int i = 0; i < n; i ++)
            cin >> t[i].x >> t[i].y;
        int len = convex_hull(t, res, n);
        double ans = 0;
        if(len == 2)
            ans = norm(res[0] - res[1]);
        else
            for(int i = 0; i < len; i ++)
                ans += norm(res[i] - res[(i + 1) % len]);
        cout << fixed << setprecision(2) << ans << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值