您的位置:首页 > 其它

hdu 1392 Surround the Trees (Convex Hull + Trick)

2013-05-26 22:21 447 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1392

  模板题,套二维凸包,然后计算凸包周长。

  唯一要注意的是两个点的时候,不用两点距离的两倍。

代码如下:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <set>
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

struct Point {
double x, y;
Point() {}
Point(double x, double y) : x(x), y(y) {}
} ;
template <class T> inline T sqr(T x) { return x * x;}
inline double ptDis(Point a, Point b) { return sqrt(sqr(a.x - b.x) + sqr(a.y - b.y));}

typedef Point Vec;
Vec operator + (Vec a, Vec b) { return Vec(a.x + b.x, a.y + b.y);}
Vec operator - (Vec a, Vec b) { return Vec(a.x - b.x, a.y - b.y);}
Vec operator * (Vec a, double p) { return Vec(a.x * p, a.y * p);}
Vec operator / (Vec a, double p) { return Vec(a.x / p, a.y / p);}

const double EPS = 1e-8;
const double PI = acos(-1.0);
inline int sgn(double x) { return fabs(x) < EPS ? 0 : (x < 0 ? -1 : 1);}
bool operator < (Point a, Point b) { return a.x < b.x || a.x == b.x && a.y < b.y;}
bool operator == (Point a, Point b) { return sgn(a.x - b.x) == 0 && sgn(a.y - b.y) == 0;}

inline double dotDet(Vec a, Vec b) { return a.x * b.x + a.y * b.y;}
inline double crossDet(Vec a, Vec b) { return a.x * b.y - a.y * b.x;}
inline double crossDet(Point o, Point a, Point b) { return crossDet(a - o, b - o);}
inline double vecLen(Vec x) { return sqrt(sqr(x.x) + sqr(x.y));}

struct Line {
Point s, t;
Line() {}
Line(Point s, Point t) : s(s), t(t) {}
Point point(double x) {
return s + (t - s) * x;
}
Vec vec() { return t - s;}
} ;
typedef Line Seg;

int andrew(Point *pt, int n, Point *ch) {
sort(pt, pt + n);
int m = 0;
for (int i = 0; i < n; i++) {
while (m > 1 && crossDet(ch[m - 1] - ch[m - 2], pt[i] - ch[m - 2]) <= 0.0) m--;
ch[m++] = pt[i];
}
int k = m;
for (int i = n - 2; i >= 0; i--) {
while (m > k && crossDet(ch[m - 1] - ch[m - 2], pt[i] - ch[m - 2]) <= 0.0) m--;
ch[m++] = pt[i];
}
if (n > 1) m--;
return m;
}

int main() {
//    freopen("in", "r", stdin);
int n;
Point p[1111], c[1111];
while (cin >> n && n) {
for (int i = 0; i < n; i++) cin >> p[i].x >> p[i].y;
int m = andrew(p, n, c);
double ans = 0;
c[m] = c[0];
for (int i = 0; i < m; i++) {
//            cout << c[i].x << ' ' << c[i].y << endl;
ans += ptDis(c[i], c[i + 1]);
}
printf("%.2f\n", m == 2 ? ans / 2.0 : ans);
}
return 0;
}


View Code

——written by Lyon
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: