QuickHull 快速凸包

#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
struct Point
{
  double x, y;
  Point(double x = 0, double y = 0): x(x), y(y) {}
};
typedef Point Vector;
typedef vector<Point> Polygon;
double Cross(Vector A, Vector B)//
{
  return A.x * B.y - A.y * B.x;
}
bool operator <(const Point &a, const Point &b)//
{
  return a.x < b.x || (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));
}
Vector operator -(Point A, Point B)//
{
  return Vector(A.x - B.x , A.y - B.y);
}
bool OnLeft(Point A, Point B, Point p)
{
  return Cross(A - B, p - A) > 0;
}
double DistanceToLine(Point p, Point A, Point B) //
{
  Vector v1 = B - A, v2 = p - A;
  return fabs(Cross(v1, v2)) / Length(v1);
}
void FindHull(const Polygon &Sk, const Point P, const Point Q, Polygon &hullPoints)
{
  if (Sk.size() == 0) return;
  Point C; Polygon S1, S2;
  double furthestDistance = 0.0;
  for (const auto &pt : Sk)
  {
    double distance = DistanceToLine(pt, P, Q);
    if (distance > furthestDistance)
    {
      furthestDistance = distance;
      C = pt;
    }
  }
  hullPoints.push_back(C);
  for (auto it = Sk.begin(); it != Sk.end(); ++it)
    (OnLeft(P, Q, *it) ? S1 : S2).push_back(*it);
  FindHull(S1, P, C, hullPoints);
  FindHull(S2, C, Q, hullPoints);
}
void QuickHull(const Polygon &s, Polygon &hullPoints)
{
  Polygon S1, S2;
  Point A = s.front(); hullPoints.push_back(A);
  Point B = s.back(); hullPoints.push_back(B);
  for (auto it = s.begin() + 1; it != s.end() - 1; ++it)
    (OnLeft(A, B, *it) ? S1 : S2).push_back(*it);
  FindHull(S1, A, B, hullPoints);
  FindHull(S2, B, A, hullPoints);
}


改造来自:https://github.com/abatilo/QuickHull/blob/master/qhull.h

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值