UVALive 6859

题目大意是给定一些点,在坐标网格上,用另外的点围成一个多边形包围这些点,并使多边形的周长尽量小,同时注意边的斜率只能是90度或者45度

思路

      凸包

为了保证周长尽量小,我们选用的点就是和给定的点的相邻点,用Graham扫描法扫描这些点,可以求出一个大体的凸包

最后处理这些边的长度时,如果是90度或者45度直接加和,否则则对这个边进行分解,再加和。

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

int N;
const int maxn = 100000 + 10;
const double eps = 1e-10;
double add(double a, double b){
    if(abs(a + b) < eps * (abs(a) + abs(b))) return 0;
    return a + b;
}

struct Point{
    double x, y;
    Point(){}
    Point(double x, double y) : x(x), y(y) {}
    Point operator + (const Point & p){
        return Point(add(x, p.x), add(y, p.y));
    }
    Point operator - (const Point & p){
        return Point(add(x,-p.x), add(y, -p.y));
    }
    Point operator * (double d){
        return Point(x * d, y * d);
    }
    double dot(const Point & p){
        return add(x * p.x, y * p.y);
    }
    double det(const Point & p){
        return add(x * p.y, -y * p.x);
    }
};

bool cmp_x(const Point & p, const Point &q){
    if(p.x != q.x) return (p.x - q.x) < 0;
    return p.y - q.y < 0;
}

vector convex_hull(Point * ps, int n){
    sort(ps, ps + n, cmp_x);
    int k = 0;
    vector qs(n * 2);
    for(int i = 0; i < n; ++i){
        while(k > 1 && (qs[k - 1] - qs[k - 2]).det(ps[i] - qs[k - 1]) <= 0) k--;
        qs[k++] = ps[i];
    }
    for(int i = n - 2, t = k; i >= 0; i--){
        while(k > t && (qs[k - 1] - qs[k - 2]).det(ps[i] - qs[k - 1]) <= 0) k--;
        qs[k++] = ps[i];
    }
    qs.resize(k - 1);
    return qs;
}

#define sqr(x) ((x)*(x))
double dist(Point & p, Point & q){
    return sqrt(sqr(p.x - q.x) + sqr(p.y - q.y));
}

Point ps[5 * maxn];

double solve(int cnt){
    vector qs = convex_hull(ps, cnt);
    double res = 0.000;
    int len = qs.size();
    for(int i = 0; i < len; ++i){
        Point tp = qs[i], tq = qs[(i + 1) % len];
        double ans = 0;
        if(tp.x == tq.x || tp.y == tq.y){
            ans = dist(tp, tq);
        }else{
            if(fabs(tp.y - tq.y) == fabs(tp.x - tq.x)) ans = dist(tp, tq);
            else {
                double dy = fabs(tp.y - tq.y), dx = fabs(tp.x - tq.x);
                ans += min(dy, dx) * sqrt(2) + fabs(dy - dx);
            }
        }
        res += ans;
    }
    return res;
}


int main()
{
    while(scanf("%d", &N) == 1){
        int cnt = 0;
        for(int i = 0; i < N; ++i){
            int x, y;
            scanf("%d %d", &x, &y);
            ps[cnt].x = x - 1;
            ps[cnt++].y = y;
            ps[cnt].x = x + 1;
            ps[cnt++].y = y;
            ps[cnt].x = x;
            ps[cnt++].y = y + 1;
            ps[cnt].x = x;
            ps[cnt++].y = y - 1;
        }
        printf("%.4f\n", solve(cnt));
    }
    return 0;
}


你可能感兴趣的:(计算几何)