UVa 11168 Airport , 凸包
生活随笔
收集整理的這篇文章主要介紹了
UVa 11168 Airport , 凸包
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:
給出平面上n個點,找一條直線,使得全部點在直線的同側。且到直線的距離之平均值盡量小。?
先求凸包
易知最優直線一定是凸包的某條邊,然后利用點到直線距離公式進行計算。
#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(a.x+b.x, a.y+b.y); } Vector operator - (const Vector& a, const Vector& b) {return Vector(a.x-b.x, a.y-b.y); } Vector operator * (const Vector& a, double p) {return Vector(a.x*p, a.y*p); } Vector operator / (const Vector& a, double p) {return Vector(a.x/p, a.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& a, const Vector& b) {return a.x*b.y - a.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[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--;ch.resize(m);return ch; }// 過兩點p1, p2的直線一般方程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%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;elsefor(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; }
總結
以上是生活随笔為你收集整理的UVa 11168 Airport , 凸包的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: click和blur 冲突???
- 下一篇: 函数声明和变量声明提升