【USACO 5.1.1】Fencing the Cows

Fencing the Cows
Hal Burch

Farmer John wishes to build a fence to contain his cows, but he's a bit short on cash right. Any fence he builds must contain all of the favorite grazing spots for his cows. Given the location of these spots, determine the length of the shortest fence which encloses them.

PROGRAM NAME: fc

INPUT FORMAT

The first line of the input file contains one integer, N. N (0 <= N <= 10,000) is the number of grazing spots that Farmer john wishes to enclose. The next N line consists of two real numbers, Xi and Yi, corresponding to the location of the grazing spots in the plane (-1,000,000 <= Xi,Yi <= 1,000,000). The numbers will be in decimal format.

SAMPLE INPUT (file fc.in)

4
4 8
4 12
5 9.3
7 8

OUTPUT FORMAT

The output should consists of one real number, the length of fence required. The output should be accurate to two decimal places.

SAMPLE OUTPUT (file fc.out)

12.00

裸的凸包题目。
不过我没有用Gift wraping.我用的是在《算法指南》上的Andrew.
效果应该说差不多,相对来说我觉得Andrew好写.
/*
TASK:fc
LANG:C++
*/

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;

const int MAXN = 10005;
const double EPS = 1e-10;

struct Vertex
{
    double x, y;
    
    Vertex() {
    }
    
    Vertex(double x0, double y0) : x(x0), y(y0) {
    }
    
    bool operator < (const Vertex &A) const
    {
        return x < A.x || (abs(x - A.x) <= EPS && y < A.y);
    }
    
    Vertex operator - (const Vertex &A)
    {
        return Vertex(x - A.x, y - A.y);
    }
    
}v[MAXN], ch[MAXN];

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

double sqr(double x)
{
    return x * x;
}

double Distance(Vertex A, Vertex B)
{
    return sqrt(sqr(A.x - B.x) + sqr(A.y - B.y));
}

int n;

int main()
{
    freopen("fc.in", "r", stdin);
    freopen("fc.out", "w", stdout);
    scanf("%d", &n);
    for (int i = 0; i < n; ++i)
        scanf("%lf%lf", &v[i].x, &v[i].y);
    sort(v, v + n);
    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];
    }
    double ans = 0;
    for (int i = 0; i < m - 1; ++i)
        ans += Distance(ch[i], ch[i + 1]);
    printf("%.2lf\n", ans);
    return 0;
}

 

posted @ 2015-11-15 16:41  albertxwz  阅读(248)  评论(0编辑  收藏  举报