描述
在直角坐标系中,给出n个顶点的坐标,求这n个点所围成的图形的周长和面积。
注意:
(1)如果所有点共线则周长按直线的长度计算,面积视为0;
(2)如果部分点共线按共线后的多边形计算;
(3)所给出的n个顶点如果能围成多边形均为突多边形。
#include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
struct Point {
double x, y;
Point(double x = 0, double y = 0) : x(x), y(y) {}
Point read() {
int a, b;
scanf("%d%d", &a, &b);
this->x = a;
this->y = b;
return *this;
}
};
typedef Point Vector;
Vector operator-(Vector a, Vector b) { return Vector(a.x - b.x, a.y - b.y); }
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 Cross(Vector a, Vector b) { return a.x * b.y - a.y * b.x; }
bool operator<(const Vector &a, const Vector &b) { return a.x < b.x || (a.x == b.x && a.y < b.y); }
int dcmp(double x) {
if (fabs(x) < EPS)return 0;
return (x > 0) ? 1 : -1;
}
double PolygonAera(Point *p, int n) {
double aera = 0.0;
for (int i = 1; i < n - 1; i++)aera += Cross(p[i] - p[0], p[i + 1] - p[0]);
return aera / 2.0;
}
double PolygonCircumference(Point *p, int n) {
double c = Length(p[0] - p[n - 1]);
for (int i = 1; i < n; i++)c += Length(p[i] - p[i - 1]);
return c;
}
int ConvexHull(Point *p, int n, Point *ch) {
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() {
int n;
while (scanf("%d", &n) == 1) {
Point s[20], ch[20];
for (int i = 0; i < n; i++)
s[i].read();
int m = ConvexHull(s, n, ch);
bool ok = false;
for (int i = 2; i < m; i++)
if (dcmp(Cross(ch[i] - ch[i - 1], ch[i - 1] - ch[i - 2])) != 0)
ok = true;
double circumference = PolygonCircumference(ch, m);
double aera = PolygonAera(ch, m);
if (ok)
printf("%.2lf\n%.2lf\n", circumference, aera);
else
printf("%.2lf\n%.2lf\n", circumference / 2.0, 0.0);
}
return 0;
}