USACO 5.1 fencing the cows——计算几何/凸包模板

终于进入第五章了,第四节最后一个题好无聊= =。

此题纯凸包模板:

/*
ID:zlqest11
LANG: C++
TASK: fc
*/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

const int N = 10005;
const double eps = 1e-6;

struct gPoint{
double x, y;
}p[N];
int n;
//the convex structure
gPoint convex[N<<1];
int vCount;

int dbcmp(double x){
if(x < -eps) return -1;
else if(x > eps) return 1;
else return 0;
}

bool cmp(const gPoint &a, const gPoint &b){
if(dbcmp(a.x-b.x) == 0)
return dbcmp(a.y-b.y)<=0;
else
return dbcmp(a.x-b.x)<=0;
}

double Dis(gPoint a, gPoint b){
double tx=b.x-a.x, ty=b.y-a.y;
return sqrt(tx*tx+ty*ty);
}

bool rCheck(const gPoint &a, const gPoint &b, const gPoint &c){
double x1, y1, x2, y2, tmp;
x1 = b.x - a.x;
y1 = b.y - a.y;
x2 = c.x - a.x;
y2 = c.y - a.y;
tmp = x1*y2-x2*y1;
return dbcmp(tmp) < 0;
}

void grahamScan(){
vCount = 2;
convex[0] = p[0];
if(n == 1) return;
convex[1] = p[1];
for(int i = 2; i < n; i++){
while(vCount>=2 && rCheck(convex[vCount-2],convex[vCount-1], p[i]))
vCount--;
convex[vCount++] = p[i];
}
for(int i = n-2; i >= 0; i--){
while(vCount>=2 && rCheck(convex[vCount-2],convex[vCount-1], p[i]))
vCount--;
convex[vCount++] = p[i];
}
}

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", &p[i].x, &p[i].y);
sort(p, p+n, cmp);
grahamScan();
double ans = 0.0;
for(int i = 1; i < vCount; i++){
ans += Dis(convex[i-1], convex[i]);
}
printf("%.2f\n", ans);
return 0;
}



你可能感兴趣的:(USACO)