题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2109
就是刘汝佳训练指南上的思路,需要注意的是只有两个点的情况。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
struct Point
{
double x, y;
Point() {}
Point(double x, double y):x(x), y(y) {}
bool operator < (const Point& a) const
{
if (x == a.x)
return y < a.y;
return x < a.x;
}
bool operator == (const Point& a) const
{
return x == a.x && y == a.y;
}
};
typedef Point Vector;
Point P[10010], convex[10010];
Vector operator - (Point A, Point B)
{
return Vector(A.x-B.x, A.y-B.y);
}
double Cross(Vector A, Vector B)
{
return A.x*B.y - A.y*B.x;
}
int ConvexHull(Point *p, int n, Point *ch)
{
sort(p, p+n);
n = unique(p, p+n) - p;
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];
}
return m;
}
int main()
{
int t;
scanf("%d",&t);
for (int Case=1; Case <=t; Case++)
{
int n;
double sum_x = 0, sum_y = 0;
scanf("%d",&n);
for (int i=0; i<n; i++)
{
scanf("%lf%lf",&P[i].x,&P[i].y);
sum_x += P[i].x;
sum_y += P[i].y;
}
int cnt = ConvexHull(P,n,convex);
double ans = 100000000000;
for (int i=0; i<cnt-1; i++)
{
double A = convex[i].y - convex[i+1].y;
double B = convex[i+1].x - convex[i].x;
double C = convex[i].x*convex[i+1].y - convex[i].y*convex[i+1].x;
double temp = (A*sum_x + B*sum_y + n*C) / sqrt(A*A + B*B);
ans = abs(temp) < ans ? abs(temp) : ans;
}
if (n <= 2)
ans = 0;
printf("Case #%d: %.3lf\n",Case, ans/n);
}
return 0;
}