Skip to content

triangle_point_counter.hpp

SECTIONGeometry INCLUDEnoya/triangle_point_counter.hpp

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.

Verified by count_points_in_triangle.

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

Implementation

View on GitHub

#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> vertices_;
  std::vector<int> point_less_, point_equal_;
  std::vector<std::vector<int>> edge_less_, edge_equal_;

  static Wide determinant(const point_type &first, const point_type &second,
                          const point_type &origin) {
    Wide first_x = Wide(first.x) - Wide(origin.x);
    Wide first_y = Wide(first.y) - Wide(origin.y);
    Wide second_x = Wide(second.x) - Wide(origin.x);
    Wide second_y = Wide(second.y) - Wide(origin.y);
    return first_x * second_y - first_y * second_x;
  }

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

public:
  triangle_point_counter(const std::vector<point_type> &vertices,
                         const std::vector<point_type> &points)
      : vertices_(vertices), point_less_(vertices.size()),
        point_equal_(vertices.size()),
        edge_less_(vertices.size(), std::vector<int>(vertices.size())),
        edge_equal_(vertices.size(), std::vector<int>(vertices.size())) {
    int vertex_count = int(vertices_.size());
    for (int vertex = 0; vertex < vertex_count; vertex++) {
      for (const auto &candidate : points) {
        if (vertices_[vertex].y != candidate.y) {
          continue;
        }
        point_less_[vertex] += candidate.x < vertices_[vertex].x;
        point_equal_[vertex] += candidate.x == vertices_[vertex].x;
      }
    }
    for (int lower = 0; lower < vertex_count; lower++) {
      for (int upper = 0; upper < vertex_count; upper++) {
        if (!(vertices_[lower].y < vertices_[upper].y)) {
          continue;
        }
        for (const auto &candidate : points) {
          if (!(vertices_[lower].y < candidate.y &&
                candidate.y < vertices_[upper].y)) {
            continue;
          }
          Wide side =
              determinant(vertices_[lower], candidate, vertices_[upper]);
          edge_less_[lower][upper] += side < 0;
          edge_equal_[lower][upper] += side == 0;
        }
      }
    }
  }

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

  int count_strictly_inside(int first, int second, int third) const {
    int n = vertex_count();
    assert(0 <= first && first < n);
    assert(0 <= second && second < n);
    assert(0 <= third && third < n);
    if (less_yx(second, first)) {
      std::swap(first, second);
    }
    if (less_yx(third, second)) {
      std::swap(second, third);
    }
    if (less_yx(second, first)) {
      std::swap(first, second);
    }

    Wide turn =
        determinant(vertices_[first], vertices_[second], vertices_[third]);
    if (turn == 0) {
      return 0;
    }
    if (vertices_[first].y == vertices_[second].y) {
      return edge_less_[second][third] -
             (edge_less_[first][third] + edge_equal_[first][third]);
    }
    if (vertices_[second].y == vertices_[third].y) {
      return edge_less_[first][third] -
             (edge_less_[first][second] + edge_equal_[first][second]);
    }
    if (turn < 0) {
      return edge_less_[first][third] - edge_less_[second][third] -
             edge_equal_[second][third] - edge_less_[first][second] -
             edge_equal_[first][second] - point_less_[second] -
             point_equal_[second];
    }
    return edge_less_[first][second] + edge_less_[second][third] +
           point_less_[second] - edge_less_[first][third] -
           edge_equal_[first][third];
  }
};

} // 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 &other) {
    x += other.x;
    y += other.y;
    return *this;
  }
  point &operator-=(const point &other) {
    x -= other.x;
    y -= other.y;
    return *this;
  }
  point &operator*=(const T &scale) {
    x *= scale;
    y *= scale;
    return *this;
  }
  point &operator/=(const T &scale) {
    x /= scale;
    y /= scale;
    return *this;
  }

  friend point operator+(point left, const point &right) {
    return left += right;
  }
  friend point operator-(point left, const point &right) {
    return left -= right;
  }
  friend point operator*(point value, const T &scale) { return value *= scale; }
  friend point operator*(const T &scale, point value) { return value *= scale; }
  friend point operator/(point value, const T &scale) { return value /= scale; }
  friend bool operator==(const point &, const point &) = default;
  friend bool operator<(const point &left, const point &right) {
    return left.x < right.x || (left.x == right.x && left.y < right.y);
  }
};

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

/// @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 - origin, b - origin).
template <class T>
T cross(const point<T> &origin, const point<T> &a, const point<T> &b) {
  return cross(a - origin, b - origin);
}

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

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

/// @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 &epsilon = T{}) {
  return sign(cross(a, b, c), epsilon);
}

/// @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 &epsilon = T{}) {
  if (orientation(a, b, p, epsilon) != 0) {
    return false;
  }
  return std::min(a.x, b.x) - epsilon <= p.x &&
         p.x <= std::max(a.x, b.x) + epsilon &&
         std::min(a.y, b.y) - epsilon <= p.y &&
         p.y <= std::max(a.y, b.y) + epsilon;
}

/// @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 &epsilon = T{}) {
  int ab_c = orientation(a, b, c, epsilon);
  int ab_d = orientation(a, b, d, epsilon);
  int cd_a = orientation(c, d, a, epsilon);
  int cd_b = orientation(c, d, b, epsilon);
  if (ab_c == 0 && on_segment(c, a, b, epsilon)) {
    return true;
  }
  if (ab_d == 0 && on_segment(d, a, b, epsilon)) {
    return true;
  }
  if (cd_a == 0 && on_segment(a, c, d, epsilon)) {
    return true;
  }
  if (cd_b == 0 && on_segment(b, c, d, epsilon)) {
    return true;
  }
  return ab_c * ab_d < 0 && cd_a * cd_b < 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 epsilon = 0) {
  point<long double> first{static_cast<long double>(a.x),
                           static_cast<long double>(a.y)};
  point<long double> second{static_cast<long double>(b.x),
                            static_cast<long double>(b.y)};
  point<long double> third{static_cast<long double>(c.x),
                           static_cast<long double>(c.y)};
  point<long double> fourth{static_cast<long double>(d.x),
                            static_cast<long double>(d.y)};
  point<long double> direction_a = second - first;
  point<long double> direction_b = fourth - third;
  long double denominator = cross(direction_a, direction_b);
  if (std::abs(denominator) <= epsilon) {
    return std::nullopt;
  }
  long double ratio = cross(third - first, direction_b) / denominator;
  return first + direction_a * ratio;
}

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

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

/// @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>> &polygon) {
  bool inside = false;
  for (int i = 0; i < int(polygon.size()); i++) {
    point<T> a = polygon[i];
    point<T> b = polygon[(i + 1) % polygon.size()];
    if (on_segment(p, a, b)) {
      return 0;
    }
    if (a.y <= p.y && p.y < b.y && orientation(a, b, p) > 0) {
      inside = !inside;
    }
    if (b.y <= p.y && p.y < a.y && orientation(a, b, p) < 0) {
      inside = !inside;
    }
  }
  return inside ? 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> vertices_;
  std::vector<int> point_less_, point_equal_;
  std::vector<std::vector<int>> edge_less_, edge_equal_;

  static Wide determinant(const point_type &first, const point_type &second,
                          const point_type &origin) {
    Wide first_x = Wide(first.x) - Wide(origin.x);
    Wide first_y = Wide(first.y) - Wide(origin.y);
    Wide second_x = Wide(second.x) - Wide(origin.x);
    Wide second_y = Wide(second.y) - Wide(origin.y);
    return first_x * second_y - first_y * second_x;
  }

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

public:
  triangle_point_counter(const std::vector<point_type> &vertices,
                         const std::vector<point_type> &points)
      : vertices_(vertices), point_less_(vertices.size()),
        point_equal_(vertices.size()),
        edge_less_(vertices.size(), std::vector<int>(vertices.size())),
        edge_equal_(vertices.size(), std::vector<int>(vertices.size())) {
    int vertex_count = int(vertices_.size());
    for (int vertex = 0; vertex < vertex_count; vertex++) {
      for (const auto &candidate : points) {
        if (vertices_[vertex].y != candidate.y) {
          continue;
        }
        point_less_[vertex] += candidate.x < vertices_[vertex].x;
        point_equal_[vertex] += candidate.x == vertices_[vertex].x;
      }
    }
    for (int lower = 0; lower < vertex_count; lower++) {
      for (int upper = 0; upper < vertex_count; upper++) {
        if (!(vertices_[lower].y < vertices_[upper].y)) {
          continue;
        }
        for (const auto &candidate : points) {
          if (!(vertices_[lower].y < candidate.y &&
                candidate.y < vertices_[upper].y)) {
            continue;
          }
          Wide side =
              determinant(vertices_[lower], candidate, vertices_[upper]);
          edge_less_[lower][upper] += side < 0;
          edge_equal_[lower][upper] += side == 0;
        }
      }
    }
  }

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

  int count_strictly_inside(int first, int second, int third) const {
    int n = vertex_count();
    assert(0 <= first && first < n);
    assert(0 <= second && second < n);
    assert(0 <= third && third < n);
    if (less_yx(second, first)) {
      std::swap(first, second);
    }
    if (less_yx(third, second)) {
      std::swap(second, third);
    }
    if (less_yx(second, first)) {
      std::swap(first, second);
    }

    Wide turn =
        determinant(vertices_[first], vertices_[second], vertices_[third]);
    if (turn == 0) {
      return 0;
    }
    if (vertices_[first].y == vertices_[second].y) {
      return edge_less_[second][third] -
             (edge_less_[first][third] + edge_equal_[first][third]);
    }
    if (vertices_[second].y == vertices_[third].y) {
      return edge_less_[first][third] -
             (edge_less_[first][second] + edge_equal_[first][second]);
    }
    if (turn < 0) {
      return edge_less_[first][third] - edge_less_[second][third] -
             edge_equal_[second][third] - edge_less_[first][second] -
             edge_equal_[first][second] - point_less_[second] -
             point_equal_[second];
    }
    return edge_less_[first][second] + edge_less_[second][third] +
           point_less_[second] - edge_less_[first][third] -
           edge_equal_[first][third];
  }
};

} // namespace noya