题解:
今天开始学习计算几何。
这是一道计算几何求凸包周长的模板题,采用Andrew算法。
第二道题改下输出即可。
最后凸包周长的求法注意第一个点和最后一个点是同一个。
代码
100ms 3MB
#include<cstdio>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 10;
int n;
struct Point {
double x, y;
Point(double x=0, double y=0):x(x),y(y) {}
}p[maxn], ch[maxn];
typedef Point Vector;
Vector operator + (Vector A, Vector B) { return Vector(A.x+B.x, A.y+B.y); }
Vector operator - (Vector A, Vector B) { return Vector(A.x-B.x, A.y-B.y); }
Vector operator * (Vector A, double p) { return Vector(A.x*p, A.y*p); }
Vector operator / (Vector A, double p) { return Vector(A.x/p, A.y/p); }
bool operator < (const Vector& a, const Vector& b) {
return a.x < b.x || (a.x == b.x && a.y < b.y);
}
const double eps = 1e-10;
int dcmp(double x) {
if(fabs(x) < eps) return 0; else return x < 0 ? -1 : 1;
}
bool operator == (const Vector& a, const Vector& b) {
return dcmp(a.x-b.x) == 0 && dcmp(a.y-b.y) == 0;
}
double Dot(Vector A, Vector B) { return A.x*B.x + A.y*B.y; }
double Length(Vector A) { return sqrt(Dot(A, A)); }
double Angle(Vector A, Vector B) { return acos(Dot(A, B) / Length(A) / Length(B)); }
double Cross(Vector A, Vector B) { return A.x*B.y - A.y*B.x; }
double Area2(Point A, Point B, Point C) { return Cross(B-A, C-A); }
int ConvexHull() {
sort(p, p+n);
int m = 0;
for(int i = 0; i < n; i++) {
while(m > 1 && Cross(ch[m-1]-ch[m-2], p[i]-ch[m-2]) <= 0) m--;
ch[m++] = p[i];
}
int k = m;
for(int i = n-2; i >= 0; i--) {
while(m > k && Cross(ch[m-1]-ch[m-2], p[i]-ch[m-2]) <= 0) m--;
ch[m++] = p[i];
}
if(n > 1) m--;
return m;
}
int main() {
scanf("%d", &n);
for(int i = 0; i < n; i++) scanf("%lf%lf", &p[i].x, &p[i].y);
int c = ConvexHull();
double ans = 0;
for(int i = 0; i < c; i++) ans += Length(ch[i]-ch[i+1]);
printf("%.1lf\n", ans);
return 0;
}
[codevs 1298] 凸包周长 [codevs 3201] 奶牛代理商 XI
原文地址:http://blog.csdn.net/qq_21110267/article/details/43604045