模板二维凸包

Posted chhokmah

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了模板二维凸包相关的知识,希望对你有一定的参考价值。

题目地址

https://www.luogu.org/problemnew/show/P2742

代码

#include <bits/stdc++.h>
#define db double 
#define N 10005
using namespace std;
template <typename T> T sqr(T x) {return x * x;}
struct Point {
    db x, y;
}p[N], s[N];
db dist(Point p1, Point p2) {
    return sqrt(sqr(p1.x - p2.x) + sqr(p1.y - p2.y));
}
bool cmp(Point p1, Point p2) {
    return (p1.x == p2.x)? (p1.y < p2.y): (p1.x < p2.x);
}
db cross(Point p1, Point p2, Point p3, Point p4) {
    return (p2.x - p1.x) * (p4.y - p3.y) - (p4.x - p3.x) * (p2.y - p1.y);
}
int n, tot;
db ans = 0;
int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i ++) scanf("%lf%lf", &p[i].x, &p[i].y);
    sort(p + 1, p + 1 + n, cmp);
    tot = 0;
    for (int i = 1; i <= n; i ++) {
        while (tot > 1 && cross(s[tot], s[tot - 1], s[tot], p[i]) <= 0) -- tot;
        s[++ tot] = p[i];
    }
    int tmp = tot;
    for (int i = n - 1; i >= 1; i --) {
        while (tot > tmp && cross(s[tot], s[tot - 1], s[tot], p[i]) <= 0) -- tot;
        s[++ tot] = p[i];
    }
    for (int i = 2; i <= tot; i ++) ans += dist(s[i], s[i - 1]);
    printf("%.2lf\n", ans);
    return 0;
}

以上是关于模板二维凸包的主要内容,如果未能解决你的问题,请参考以下文章

P2742 [USACO5.1]圈奶牛Fencing the Cows /模板二维凸包(计算几何)(凸包)

P2742 [USACO5.1]圈奶牛Fencing the Cows /模板二维凸包(计算几何)(凸包)

Luogu P2742 模板二维凸包

模板二维凸包 / [USACO5.1]圈奶牛Fencing the Cows

P2742 模板二维凸包 / [USACO5.1]圈奶牛Fencing the Cows

P2742 模板二维凸包 / [USACO5.1]圈奶牛Fencing the Cows