Surround the Trees - http://acm.hdu.edu.cn/showproblem.php?pid=1392
代码
// hdu 1392 Surround the Tress
#include<bits/stdc++.h>
#define LL long long
using namespace std;
#define MXN 110
struct Point{
LL x, y;
// 与点p是否是为同一个点
bool operator==(const Point &p){
return x == p.x && y == p.y;
}
// 1:y最小,2:y相等时x最小
bool operator<(const Point &p){
if(y == p.y) return x < p.x;
return y < p.y;
}
// 点p(x,y)与点p1和p2构成的向量p->p1、p->p2的叉积
LL cross(const Point &p1, const Point &p2){
return (p1.x - x)*(p2.y - y) - (p1.y - y)*(p2.x - x);
}
double distance(const Point &p){
return sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));
}
};
int main(){
int n, q[MXN];
Point tr[MXN];
while(scanf("%d", &n) && n){
Point p = {32768, 32768};
for(int i = 0; i < n; i++){
scanf("%lld %lld", &tr[i].x, &tr[i].y);
if(tr[i] < p) p = tr[i];
}
if(n == 1){
printf("%.2f\n", 0);
continue;
}
else if(n == 2){
printf("%.2f\n", tr[0].distance(tr[1])); // 不明白为什么不是算2倍?
continue;
}
sort(tr, tr+n, [&p](Point &p1, Point &p2){
if(p1 == p || p2 == p) return p1 == p;
LL res = p.cross(p1, p2);
if(res) return res > 0;
return p1.y < p2.y;
});
int k = 1;
q[0] = 0, q[1] = 1;
for(int i = 2; i <= n; i++){
while(tr[q[k-1]].cross(tr[q[k]], tr[(i)%n]) < 0) k--;
q[++k] = i == n ? 0 : i;
}
double dis = 0;
for(int i = 1; i <= k; i++) dis += tr[q[i-1]].distance(tr[q[i]]);
printf("%.2f\n", dis);
}
return 0;
}