Skip to content

triangle_point_counter.hpp

SECTIONGeometry INCLUDEnoya/triangle_point_counter.hpp

预处理固定点集后,快速统计以其中三点为顶点的开三角形内部有多少点。

Complexity: Time: O(n^2 m) preprocessing and O(1) per triangle query. Space: O(n^2), for n query vertices and m points being counted.

AC 记录:count_points_in_triangle

跳到代码 · GitHub ↗

Implementation

当前头文件,省略 include guard;依赖见 #include

/// @complexity Time: O(n^2 m) preprocessing and O(1) per triangle query.
/// Space: O(n^2), for n query vertices and m points being counted.

#include "noya/geometry_base.hpp"

#include <algorithm>
#include <cassert>
#include <vector>

namespace noya {

/// @brief Count points strictly inside triangles whose vertices come from a
/// fixed set. For every upward-directed vertex pair, preprocessing counts
/// points at intermediate heights strictly left of its supporting line and on
/// that line. Horizontal-ray counts are stored at each vertex as well. Sorting
/// a query's three vertices by (y, x) decomposes its open interior into a
/// signed combination of at most three such half-open strips and one horizontal
/// ray, with line and vertex equality counts removing every boundary point.
template <class Coordinate = long long, class Wide = long long>
class triangle_point_counter {
public:
  using point_type = point<Coordinate>;

private:
  std::vector<point_type> pt_;
  std::vector<int> plt, peq;
  std::vector<std::vector<int>> elt, eeq;

  static Wide determinant(const point_type &lhs, const point_type &rhs,
                          const point_type &o) {
    Wide x1 = Wide(lhs.x) - Wide(o.x);
    Wide y1 = Wide(lhs.y) - Wide(o.y);
    Wide x2 = Wide(rhs.x) - Wide(o.x);
    Wide y2 = Wide(rhs.y) - Wide(o.y);
    return x1 * y2 - y1 * x2;
  }

  bool less_yx(int lhs, int rhs) const {
    const auto &a = pt_[lhs];
    const auto &b = pt_[rhs];
    return a.y < b.y || (!(b.y < a.y) && a.x < b.x);
  }

public:
  triangle_point_counter(const std::vector<point_type> &vs,
                         const std::vector<point_type> &pt)
      : pt_(vs), plt(vs.size()), peq(vs.size()),
        elt(vs.size(), std::vector<int>(vs.size())),
        eeq(vs.size(), std::vector<int>(vs.size())) {
    int nv = int(pt_.size());
    for (int u = 0; u < nv; u++) {
      for (const auto &can : pt) {
        if (pt_[u].y != can.y) {
          continue;
        }
        plt[u] += can.x < pt_[u].x;
        peq[u] += can.x == pt_[u].x;
      }
    }
    for (int lo = 0; lo < nv; lo++) {
      for (int hi = 0; hi < nv; hi++) {
        if (!(pt_[lo].y < pt_[hi].y)) {
          continue;
        }
        for (const auto &can : pt) {
          if (!(pt_[lo].y < can.y && can.y < pt_[hi].y)) {
            continue;
          }
          Wide sd = determinant(pt_[lo], can, pt_[hi]);
          elt[lo][hi] += sd < 0;
          eeq[lo][hi] += sd == 0;
        }
      }
    }
  }

  int vertex_count() const { return int(pt_.size()); }

  int count_strictly_inside(int lhs, int rhs, int c) const {
    int n = vertex_count();
    assert(0 <= lhs && lhs < n);
    assert(0 <= rhs && rhs < n);
    assert(0 <= c && c < n);
    if (less_yx(rhs, lhs)) {
      std::swap(lhs, rhs);
    }
    if (less_yx(c, rhs)) {
      std::swap(rhs, c);
    }
    if (less_yx(rhs, lhs)) {
      std::swap(lhs, rhs);
    }

    Wide rot = determinant(pt_[lhs], pt_[rhs], pt_[c]);
    if (rot == 0) {
      return 0;
    }
    if (pt_[lhs].y == pt_[rhs].y) {
      return elt[rhs][c] - (elt[lhs][c] + eeq[lhs][c]);
    }
    if (pt_[rhs].y == pt_[c].y) {
      return elt[lhs][c] - (elt[lhs][rhs] + eeq[lhs][rhs]);
    }
    if (rot < 0) {
      return elt[lhs][c] - elt[rhs][c] - eeq[rhs][c] - elt[lhs][rhs] -
             eeq[lhs][rhs] - plt[rhs] - peq[rhs];
    }
    return elt[lhs][rhs] + elt[rhs][c] + plt[rhs] - elt[lhs][c] - eeq[lhs][c];
  }
};

} // namespace noya
#ifndef NOYA_TRIANGLE_POINT_COUNTER_HPP
#define NOYA_TRIANGLE_POINT_COUNTER_HPP 1

/// @complexity Time: O(n^2 m) preprocessing and O(1) per triangle query.
/// Space: O(n^2), for n query vertices and m points being counted.

#include "noya/geometry_base.hpp"

#include <algorithm>
#include <cassert>
#include <vector>

namespace noya {

/// @brief Count points strictly inside triangles whose vertices come from a
/// fixed set. For every upward-directed vertex pair, preprocessing counts
/// points at intermediate heights strictly left of its supporting line and on
/// that line. Horizontal-ray counts are stored at each vertex as well. Sorting
/// a query's three vertices by (y, x) decomposes its open interior into a
/// signed combination of at most three such half-open strips and one horizontal
/// ray, with line and vertex equality counts removing every boundary point.
template <class Coordinate = long long, class Wide = long long>
class triangle_point_counter {
public:
  using point_type = point<Coordinate>;

private:
  std::vector<point_type> pt_;
  std::vector<int> plt, peq;
  std::vector<std::vector<int>> elt, eeq;

  static Wide determinant(const point_type &lhs, const point_type &rhs,
                          const point_type &o) {
    Wide x1 = Wide(lhs.x) - Wide(o.x);
    Wide y1 = Wide(lhs.y) - Wide(o.y);
    Wide x2 = Wide(rhs.x) - Wide(o.x);
    Wide y2 = Wide(rhs.y) - Wide(o.y);
    return x1 * y2 - y1 * x2;
  }

  bool less_yx(int lhs, int rhs) const {
    const auto &a = pt_[lhs];
    const auto &b = pt_[rhs];
    return a.y < b.y || (!(b.y < a.y) && a.x < b.x);
  }

public:
  triangle_point_counter(const std::vector<point_type> &vs,
                         const std::vector<point_type> &pt)
      : pt_(vs), plt(vs.size()), peq(vs.size()),
        elt(vs.size(), std::vector<int>(vs.size())),
        eeq(vs.size(), std::vector<int>(vs.size())) {
    int nv = int(pt_.size());
    for (int u = 0; u < nv; u++) {
      for (const auto &can : pt) {
        if (pt_[u].y != can.y) {
          continue;
        }
        plt[u] += can.x < pt_[u].x;
        peq[u] += can.x == pt_[u].x;
      }
    }
    for (int lo = 0; lo < nv; lo++) {
      for (int hi = 0; hi < nv; hi++) {
        if (!(pt_[lo].y < pt_[hi].y)) {
          continue;
        }
        for (const auto &can : pt) {
          if (!(pt_[lo].y < can.y && can.y < pt_[hi].y)) {
            continue;
          }
          Wide sd = determinant(pt_[lo], can, pt_[hi]);
          elt[lo][hi] += sd < 0;
          eeq[lo][hi] += sd == 0;
        }
      }
    }
  }

  int vertex_count() const { return int(pt_.size()); }

  int count_strictly_inside(int lhs, int rhs, int c) const {
    int n = vertex_count();
    assert(0 <= lhs && lhs < n);
    assert(0 <= rhs && rhs < n);
    assert(0 <= c && c < n);
    if (less_yx(rhs, lhs)) {
      std::swap(lhs, rhs);
    }
    if (less_yx(c, rhs)) {
      std::swap(rhs, c);
    }
    if (less_yx(rhs, lhs)) {
      std::swap(lhs, rhs);
    }

    Wide rot = determinant(pt_[lhs], pt_[rhs], pt_[c]);
    if (rot == 0) {
      return 0;
    }
    if (pt_[lhs].y == pt_[rhs].y) {
      return elt[rhs][c] - (elt[lhs][c] + eeq[lhs][c]);
    }
    if (pt_[rhs].y == pt_[c].y) {
      return elt[lhs][c] - (elt[lhs][rhs] + eeq[lhs][rhs]);
    }
    if (rot < 0) {
      return elt[lhs][c] - elt[rhs][c] - eeq[rhs][c] - elt[lhs][rhs] -
             eeq[lhs][rhs] - plt[rhs] - peq[rhs];
    }
    return elt[lhs][rhs] + elt[rhs][c] + plt[rhs] - elt[lhs][c] - eeq[lhs][c];
  }
};

} // namespace noya

#endif // NOYA_TRIANGLE_POINT_COUNTER_HPP
#include <algorithm>
#include <cassert>
#include <cmath>
#include <optional>
#include <vector>

/// @complexity Time: O(n^2 m) preprocessing and O(1) per triangle query.
/// Space: O(n^2), for n query vertices and m points being counted.

/// @complexity Time: O(1) per primitive; O(n log n) for convex hull.
/// Space: O(1) per primitive and O(n) for hull construction.

namespace noya {

/// @brief Two-dimensional point with vector arithmetic and lexicographic order.
template <class T> struct point {
  T x{};
  T y{};

  point() = default;
  point(T x_, T y_) : x(x_), y(y_) {}

  point &operator+=(const point &rhs) {
    x += rhs.x;
    y += rhs.y;
    return *this;
  }
  point &operator-=(const point &rhs) {
    x -= rhs.x;
    y -= rhs.y;
    return *this;
  }
  point &operator*=(const T &scl) {
    x *= scl;
    y *= scl;
    return *this;
  }
  point &operator/=(const T &scl) {
    x /= scl;
    y /= scl;
    return *this;
  }

  friend point operator+(point l, const point &r) { return l += r; }
  friend point operator-(point l, const point &r) { return l -= r; }
  friend point operator*(point val, const T &scl) { return val *= scl; }
  friend point operator*(const T &scl, point val) { return val *= scl; }
  friend point operator/(point val, const T &scl) { return val /= scl; }
  friend bool operator==(const point &, const point &) = default;
  friend bool operator<(const point &l, const point &r) {
    return l.x < r.x || (l.x == r.x && l.y < r.y);
  }
};

/// @brief Circle represented by a center and a nonnegative radius.
template <class Real> struct circle {
  point<Real> o;
  Real r1{};
};

/// @brief Return the dot product of two vectors.
template <class T> T dot(const point<T> &a, const point<T> &b) {
  return a.x * b.x + a.y * b.y;
}

/// @brief Return the signed cross product of two vectors.
template <class T> T cross(const point<T> &a, const point<T> &b) {
  return a.x * b.y - a.y * b.x;
}

/// @brief Return cross(a - o1, b - o1).
template <class T>
T cross(const point<T> &o1, const point<T> &a, const point<T> &b) {
  return cross(a - o1, b - o1);
}

/// @brief Return the squared Euclidean norm.
template <class T> T norm2(const point<T> &val) { return dot(val, val); }

/// @brief Compare a value with zero using an optional absolute tolerance.
template <class T> int sign(const T &val, const T &eps = T{}) {
  return (val > eps) - (val < -eps);
}

/// @brief Return -1, 0, or 1 for a clockwise, collinear, or counter-clockwise
/// turn.
template <class T>
int orientation(const point<T> &a, const point<T> &b, const point<T> &c,
                const T &eps = T{}) {
  return sign(cross(a, b, c), eps);
}

/// @brief Test whether p lies on the closed segment [a, b].
template <class T>
bool on_segment(const point<T> &p, const point<T> &a, const point<T> &b,
                const T &eps = T{}) {
  if (orientation(a, b, p, eps) != 0) {
    return false;
  }
  return std::min(a.x, b.x) - eps <= p.x && p.x <= std::max(a.x, b.x) + eps &&
         std::min(a.y, b.y) - eps <= p.y && p.y <= std::max(a.y, b.y) + eps;
}

/// @brief Test whether the closed segments [a, b] and [c, d] intersect.
template <class T>
bool segments_intersect(const point<T> &a, const point<T> &b, const point<T> &c,
                        const point<T> &d, const T &eps = T{}) {
  int s1 = orientation(a, b, c, eps);
  int s2 = orientation(a, b, d, eps);
  int s3 = orientation(c, d, a, eps);
  int s4 = orientation(c, d, b, eps);
  if (s1 == 0 && on_segment(c, a, b, eps)) {
    return true;
  }
  if (s2 == 0 && on_segment(d, a, b, eps)) {
    return true;
  }
  if (s3 == 0 && on_segment(a, c, d, eps)) {
    return true;
  }
  if (s4 == 0 && on_segment(b, c, d, eps)) {
    return true;
  }
  return s1 * s2 < 0 && s3 * s4 < 0;
}

/// @brief Intersect the infinite lines through (a, b) and (c, d), returning
/// nullopt when they are parallel or coincident.
template <class T>
std::optional<point<long double>>
line_intersection(const point<T> &a, const point<T> &b, const point<T> &c,
                  const point<T> &d, long double eps = 0) {
  point<long double> lhs{static_cast<long double>(a.x),
                         static_cast<long double>(a.y)};
  point<long double> b1{static_cast<long double>(b.x),
                        static_cast<long double>(b.y)};
  point<long double> z{static_cast<long double>(c.x),
                       static_cast<long double>(c.y)};
  point<long double> d1{static_cast<long double>(d.x),
                        static_cast<long double>(d.y)};
  point<long double> da = b1 - lhs;
  point<long double> db = d1 - z;
  long double den = cross(da, db);
  if (std::abs(den) <= eps) {
    return std::nullopt;
  }
  long double rat = cross(z - lhs, db) / den;
  return lhs + da * rat;
}

/// @brief Return the convex hull in counter-clockwise order without repetition.
template <class T>
std::vector<point<T>> convex_hull(std::vector<point<T>> pt, bool kc = false) {
  std::sort(pt.begin(), pt.end());
  pt.erase(std::unique(pt.begin(), pt.end()), pt.end());
  if (pt.size() <= 1) {
    return pt;
  }
  bool col = true;
  for (int i = 2; i < int(pt.size()); i++) {
    col &= orientation(pt[0], pt[1], pt[i]) == 0;
  }
  if (kc && col) {
    return pt;
  }
  std::vector<point<T>> lo, hi;
  for (const point<T> &p : pt) {
    while (lo.size() >= 2) {
      int rot = orientation(lo[lo.size() - 2], lo.back(), p);
      if (rot > 0 || (kc && rot == 0)) {
        break;
      }
      lo.pop_back();
    }
    lo.push_back(p);
  }
  for (auto it = pt.rbegin(); it != pt.rend(); ++it) {
    while (hi.size() >= 2) {
      int rot = orientation(hi[hi.size() - 2], hi.back(), *it);
      if (rot > 0 || (kc && rot == 0)) {
        break;
      }
      hi.pop_back();
    }
    hi.push_back(*it);
  }
  lo.pop_back();
  hi.pop_back();
  lo.insert(lo.end(), hi.begin(), hi.end());
  return lo;
}

/// @brief Return twice the signed area of a polygon.
template <class T> T polygon_area2(const std::vector<point<T>> &pg) {
  T res{};
  for (int i = 0; i < int(pg.size()); i++) {
    res += cross(pg[i], pg[(i + 1) % pg.size()]);
  }
  return res;
}

/// @brief Classify a point relative to a polygon: -1 outside, 0 boundary, 1
/// inside.
template <class T>
int point_in_polygon(const point<T> &p, const std::vector<point<T>> &pg) {
  bool in = false;
  for (int i = 0; i < int(pg.size()); i++) {
    point<T> a = pg[i];
    point<T> b = pg[(i + 1) % pg.size()];
    if (on_segment(p, a, b)) {
      return 0;
    }
    if (a.y <= p.y && p.y < b.y && orientation(a, b, p) > 0) {
      in = !in;
    }
    if (b.y <= p.y && p.y < a.y && orientation(a, b, p) < 0) {
      in = !in;
    }
  }
  return in ? 1 : -1;
}

/// @brief Return the Euclidean distance between two points.
template <class T> long double distance(const point<T> &a, const point<T> &b) {
  return std::hypot(
      static_cast<long double>(a.x) - static_cast<long double>(b.x),
      static_cast<long double>(a.y) - static_cast<long double>(b.y));
}

} // namespace noya

namespace noya {

/// @brief Count points strictly inside triangles whose vertices come from a
/// fixed set. For every upward-directed vertex pair, preprocessing counts
/// points at intermediate heights strictly left of its supporting line and on
/// that line. Horizontal-ray counts are stored at each vertex as well. Sorting
/// a query's three vertices by (y, x) decomposes its open interior into a
/// signed combination of at most three such half-open strips and one horizontal
/// ray, with line and vertex equality counts removing every boundary point.
template <class Coordinate = long long, class Wide = long long>
class triangle_point_counter {
public:
  using point_type = point<Coordinate>;

private:
  std::vector<point_type> pt_;
  std::vector<int> plt, peq;
  std::vector<std::vector<int>> elt, eeq;

  static Wide determinant(const point_type &lhs, const point_type &rhs,
                          const point_type &o) {
    Wide x1 = Wide(lhs.x) - Wide(o.x);
    Wide y1 = Wide(lhs.y) - Wide(o.y);
    Wide x2 = Wide(rhs.x) - Wide(o.x);
    Wide y2 = Wide(rhs.y) - Wide(o.y);
    return x1 * y2 - y1 * x2;
  }

  bool less_yx(int lhs, int rhs) const {
    const auto &a = pt_[lhs];
    const auto &b = pt_[rhs];
    return a.y < b.y || (!(b.y < a.y) && a.x < b.x);
  }

public:
  triangle_point_counter(const std::vector<point_type> &vs,
                         const std::vector<point_type> &pt)
      : pt_(vs), plt(vs.size()), peq(vs.size()),
        elt(vs.size(), std::vector<int>(vs.size())),
        eeq(vs.size(), std::vector<int>(vs.size())) {
    int nv = int(pt_.size());
    for (int u = 0; u < nv; u++) {
      for (const auto &can : pt) {
        if (pt_[u].y != can.y) {
          continue;
        }
        plt[u] += can.x < pt_[u].x;
        peq[u] += can.x == pt_[u].x;
      }
    }
    for (int lo = 0; lo < nv; lo++) {
      for (int hi = 0; hi < nv; hi++) {
        if (!(pt_[lo].y < pt_[hi].y)) {
          continue;
        }
        for (const auto &can : pt) {
          if (!(pt_[lo].y < can.y && can.y < pt_[hi].y)) {
            continue;
          }
          Wide sd = determinant(pt_[lo], can, pt_[hi]);
          elt[lo][hi] += sd < 0;
          eeq[lo][hi] += sd == 0;
        }
      }
    }
  }

  int vertex_count() const { return int(pt_.size()); }

  int count_strictly_inside(int lhs, int rhs, int c) const {
    int n = vertex_count();
    assert(0 <= lhs && lhs < n);
    assert(0 <= rhs && rhs < n);
    assert(0 <= c && c < n);
    if (less_yx(rhs, lhs)) {
      std::swap(lhs, rhs);
    }
    if (less_yx(c, rhs)) {
      std::swap(rhs, c);
    }
    if (less_yx(rhs, lhs)) {
      std::swap(lhs, rhs);
    }

    Wide rot = determinant(pt_[lhs], pt_[rhs], pt_[c]);
    if (rot == 0) {
      return 0;
    }
    if (pt_[lhs].y == pt_[rhs].y) {
      return elt[rhs][c] - (elt[lhs][c] + eeq[lhs][c]);
    }
    if (pt_[rhs].y == pt_[c].y) {
      return elt[lhs][c] - (elt[lhs][rhs] + eeq[lhs][rhs]);
    }
    if (rot < 0) {
      return elt[lhs][c] - elt[rhs][c] - eeq[rhs][c] - elt[lhs][rhs] -
             eeq[lhs][rhs] - plt[rhs] - peq[rhs];
    }
    return elt[lhs][rhs] + elt[rhs][c] + plt[rhs] - elt[lhs][c] - eeq[lhs][c];
  }
};

} // namespace noya