Ultraviolet A 11168 Airport, convex bag, 11168 convex bag
Question:
Give n points on the plane, find a straight line, so that all points in the same side of the straight line, and the average distance to the straight line is as small as possible.
First find the convex hull
It is easy to know that the optimal straight line must be an edge of a convex hull, and then calculated using the point-to-line distance formula.
# Include <cstdio> # include <cstring> # include <vector> # include <cmath> # include <algorithm> # include <iostream> using namespace std; struct Point {int x, y; Point (int x = 0, int y = 0): x (x), y (y) {}}; typedef Point Vector; vector operator + (const Vector & a, const Vector & B) {return Vector (. x + B. x,. y + B. y);} Vector operator-(const Vector & a, const Vector & B) {return Vector (. x-b.x,. y-b.y);} Vector operator * (const Vector & a, double p) {return Vector (. x * p,. y * p);} Vector operator/(const Vector & a, double p) {return Vector (. x/p,. y/p);} bool operator <(const Point & p1, const Point & p2) {return p1.x <p2.x | (p1.x = p2.x & p1.y <p2.y );} bool operator = (const Point & p1, const Point & p2) {return p1.x = p2.x & p1.y = p2.y;} int Cross (const Vector &, const Vector & B) {return. x * B. y-. y * B. x;} vector <Point> ConvexHull (vector <Point> p) {sort (p. begin (), p. end (); p. erase (unique (p. begin (), p. end (), p. end (); int n = p. size (); int m = 0; vector <Point> ch (n + 1); for (int I = 0; I <n; ++ I) {while (m> 1 & Cross (ch [s-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 [s-1]-ch [m-2], p [I]-ch [m-2]) <= 0) m --; ch [m ++] = p [I];} if (n> 1) m --; ch. resize (m); return ch;} // over two point p1, p2 linear General Equation ax + by + c = 0 // (x2-x1) (y-y1) = (y2-y1) (x-x1) void getLineGeneralEquation (const Point & p1, const Point & p2, double & a, double & B, double & c) {a = p2.y-p1.y; B = p1.x-p2.x; c =-a * p1.x-B * p1.y;} int main () {int t, n, I, j; scanf ("% d ", & t); for (int cas = 1; cas <= t; ++ cas) {scanf ("% d", & n); int x, y; vector <Point> P; double sumx = 0, sumy = 0; for (I = 0; I <n; ++ I) {scanf ("% d ", & x, & y); sumx + = x; sumy + = y; P. push_back (Point (x, y);} P = ConvexHull (P); int m = P. size (); double ans = 1e9; if (m <= 2) ans = 0; else for (I = 0; I <m; ++ I) {j = (I + 1) % m; double A, B, C; getLineGeneralEquation (P [I], P [j], A, B, C ); double tmp = fabs (A * sumx + B * sumy + C * n)/sqrt (A * A + B * B); ans = min (ans, tmp );} printf ("Case # % d: %. 3f \ n ", cas, ans/n);} return 0 ;}