競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。
通常版・コンパイラ共通 · この版の一覧へ
通常版・GCC専用 · この版の一覧へ
通常版・Clang専用 · この版の一覧へ
通常版・MSVC専用 · この版の一覧へ
速度優先版・コンパイラ共通 · この版の一覧へ
速度優先版・GCC専用 · この版の一覧へ
速度優先版・Clang専用 · この版の一覧へ
速度優先版・MSVC専用 · この版の一覧へ
同じ凸多角形に対して、多数の点が内部・境界・外部のどこにあるかを調べます。頂点は辺に沿って並べます。時計回りと反時計回りのどちらでも構築でき、辺の途中の点や連続する同じ点が含まれていても使えます。
using sirkit::geo::Location;
using sirkit::geo::PointI;
std::vector<PointI> polygon{{0, 0}, {4, 0}, {4, 3}, {0, 3}};
sirkit::geo::ConvexPolygonLocator locator(polygon);
assert(locator.locate({2, 1}) == Location::Inside);
assert(locator.locate({4, 1}) == Location::Boundary);
assert(locator.locate({5, 1}) == Location::Outside);
空の凸多角形では Outside を返します。点や線分に退化した場合、その点・線分上は Boundary です。座標差とその積が Point の計算型に収まる整数座標を渡します。
頂点数を n とすると、構築は O(n+1) 時間と領域、各照会は O(log(n+2)) 時間です。辺の並びが凸かどうかの検査は呼び出し側が担います。
[geo::Epsilon]
Epsilon{abs,rel}: 非負有限の絶対・相対許容幅(既定は各1e-12L)。
tolerance(scale): abs + rel * abs(scale) を返す。O(1)。
[geo::Point]
Point<T,C=DefaultCalc<T>>{x,y}: 符号付き整数/浮動小数点の集成体。座標・座標演算はT、差・積・和はCに収まる有限入力。
DefaultCalc<T>: 整数は対応環境で128ビット拡張、標準代替はint64_t。浮動小数点はT。
PointI/PointD/PointLD/RealPoint: int64_t/double/long double/long doubleのPoint。Value/Calc/Realは座標/計算/距離の型。
比較は座標の完全一致・辞書順。単項-, +,-,*,+=,-=,*= は座標演算、点同士の * は内積、^ は外積。O(1)。
dot/cross/norm2/dist2/orient は C、norm/dist は Real、ccw は符号を返す。dist2/orient の差は C で計算する。
rotated90(k)/rot90(k) は反時計回り90度の k 倍のコピー/更新、arg は偏角。O(1)。
浮動小数点専用: /,/= は非零スカラー除算、rotated/rot はラジアン回転、normalized は非零点の単位化。
almost_equal は成分別の誤差比較。cast<U,D>() は座標型変換。arg_cmp は零点を先頭に偏角・距離順。O(1)。
浮動 arg_cmp は丸めた偏角が等しければ距離順。ostream は (x,y) を出力する。O(1)。
[geo::点の関数]
点の関数。座標は有限、整数の差・積は C に収まる入力を扱う。
predicate_sign<T,C>(value,scale,eps): 整数は厳密、実数は許容幅で -1/0/1 を返す。O(1)。
orientation(a,b,c,eps): 左折1、直進0、右折-1。整数では厳密。O(1)。
to_real(p): long double 座標へ変換する。O(1)。
distance(p,q): 2点間距離を Point::Real で返す。O(1)。
[geo::Location]
Location: containsの戻り値。Outside/Boundary/Insideは外部/境界/内部。
[geo::ConvexPolygonLocator<T,C>]
ConvexPolygonLocator(vertices = {}): 周回順の凸多角形を受け取る。時計回り・反時計回り、辺上の中間点、連続した重複点を扱う。O(n+1)時間・領域。
locate(p): Outside/Boundary/Insideで外部・境界・内部を返す。空・点・線分も扱う。O(log(n+2))。
座標型Tと計算型Cは符号付き整数。判定に使う座標差とその積がCに収まること。
通常版の検証結果です。
| 問題 | プログラム | 現行ソースの状態 | 提出結果 |
|---|---|---|---|
| ABC296 G - Polygon and Points | convex_polygon_locator.cpp | 未提出 | — |
✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。
| 検査 | 状態 |
|---|---|
| 正常系 | 未実施 |
| 失敗系 | 未測定 |
| Library Checker公式ケース | 無し |
| 性能測定 | 未実施 |
| ASan/UBSan | 未実施 |
| カバレッジ | 未実施 |
到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。
// SPDX-License-Identifier: CC0-1.0
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/convex_polygon_locator.md
//
// API一覧
// [geo::Epsilon]
// Epsilon{abs,rel}: 非負有限の絶対・相対許容幅(既定は各1e-12L)。
// tolerance(scale): abs + rel * abs(scale) を返す。O(1)。
//
// [geo::Point]
// Point<T,C=DefaultCalc<T>>{x,y}: 符号付き整数/浮動小数点の集成体。座標・座標演算はT、差・積・和はCに収まる有限入力。
// DefaultCalc<T>: 整数は対応環境で128ビット拡張、標準代替はint64_t。浮動小数点はT。
// PointI/PointD/PointLD/RealPoint: int64_t/double/long double/long doubleのPoint。Value/Calc/Realは座標/計算/距離の型。
// 比較は座標の完全一致・辞書順。単項-, +,-,*,+=,-=,*= は座標演算、点同士の * は内積、^ は外積。O(1)。
// dot/cross/norm2/dist2/orient は C、norm/dist は Real、ccw は符号を返す。dist2/orient の差は C で計算する。
// rotated90(k)/rot90(k) は反時計回り90度の k 倍のコピー/更新、arg は偏角。O(1)。
// 浮動小数点専用: /,/= は非零スカラー除算、rotated/rot はラジアン回転、normalized は非零点の単位化。
// almost_equal は成分別の誤差比較。cast<U,D>() は座標型変換。arg_cmp は零点を先頭に偏角・距離順。O(1)。
// 浮動 arg_cmp は丸めた偏角が等しければ距離順。ostream は (x,y) を出力する。O(1)。
//
// [geo::点の関数]
// 点の関数。座標は有限、整数の差・積は C に収まる入力を扱う。
// predicate_sign<T,C>(value,scale,eps): 整数は厳密、実数は許容幅で -1/0/1 を返す。O(1)。
// orientation(a,b,c,eps): 左折1、直進0、右折-1。整数では厳密。O(1)。
// to_real(p): long double 座標へ変換する。O(1)。
// distance(p,q): 2点間距離を Point::Real で返す。O(1)。
//
// [geo::Location]
// Location: containsの戻り値。Outside/Boundary/Insideは外部/境界/内部。
//
// [geo::ConvexPolygonLocator<T,C>]
// ConvexPolygonLocator(vertices = {}): 周回順の凸多角形を受け取る。時計回り・反時計回り、辺上の中間点、連続した重複点を扱う。O(n+1)時間・領域。
// locate(p): Outside/Boundary/Insideで外部・境界・内部を返す。空・点・線分も扱う。O(log(n+2))。
// 座標型Tと計算型Cは符号付き整数。判定に使う座標差とその積がCに収まること。
// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <array>
#include <cmath>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <numbers>
#include <optional>
#include <ostream>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>
// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_GEO_EPSILON_DEFINED
#define SIRKIT_GEO_EPSILON_DEFINED
namespace geo {
struct Epsilon {
long double abs = 1e-12L;
long double rel = 1e-12L;
constexpr long double tolerance(long double scale) const {
if consteval {
// 実行時のfabsに依存せず、負のゼロも正のゼロへ揃える。
const long double magnitude = scale == 0 ? 0.0L : (scale < 0 ? -scale : scale);
return abs + rel * magnitude;
}
return abs + rel * std::abs(scale);
}
};
}
#endif
#ifndef SIRKIT_GEO_POINT_DEFINED
#define SIRKIT_GEO_POINT_DEFINED
namespace geo {
#if defined(__SIZEOF_INT128__) && !defined(GEO_DISABLE_INT128) && !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC)
template<class T> using DefaultCalc = std::conditional_t<std::is_integral_v<T>, __int128_t, T>;
#else
template<class T> using DefaultCalc = std::conditional_t<std::is_integral_v<T>, std::int64_t, T>;
#endif
template<class T, class C = DefaultCalc<T>>
struct Point {
static_assert((std::is_integral_v<T> && std::is_signed_v<T>) || std::is_floating_point_v<T>);
using Value = T;
using Calc = C;
using Real = std::conditional_t<std::is_floating_point_v<T>, T, long double>;
T x = 0;
T y = 0;
constexpr bool operator==(const Point& p) const { return x == p.x && y == p.y; }
constexpr bool operator!=(const Point& p) const { return !(*this == p); }
constexpr bool operator<(const Point& p) const { return x < p.x || (x == p.x && y < p.y); }
constexpr bool operator>(const Point& p) const { return p < *this; }
constexpr bool operator<=(const Point& p) const { return !(p < *this); }
constexpr bool operator>=(const Point& p) const { return !(*this < p); }
constexpr Point operator+(const Point& p) const {
return {T(C(x) + C(p.x)), T(C(y) + C(p.y))};
}
constexpr Point operator-(const Point& p) const {
return {T(C(x) - C(p.x)), T(C(y) - C(p.y))};
}
constexpr Point operator-() const {
return {T(-C(x)), T(-C(y))};
}
constexpr Point& operator+=(const Point& p) { return *this = *this + p; }
constexpr Point& operator-=(const Point& p) { return *this = *this - p; }
constexpr Point operator*(T k) const {
return {T(C(x) * C(k)), T(C(y) * C(k))};
}
template<std::floating_point U> requires std::is_integral_v<T>
Point operator*(U) const = delete;
constexpr Point& operator*=(T k) { return *this = *this * k; }
template<std::floating_point U> requires std::is_integral_v<T>
Point& operator*=(U) = delete;
friend constexpr Point operator*(T k, const Point& p) { return p * k; }
template<std::floating_point U> requires std::is_integral_v<T>
friend Point operator*(U, const Point&) = delete;
Point operator/(T k) const requires std::is_floating_point_v<T> {
if (k == 0) throw std::domain_error("zero divisor");
return {T(C(x) / C(k)), T(C(y) / C(k))};
}
Point& operator/=(T k) requires std::is_floating_point_v<T> { return *this = *this / k; }
constexpr C dot(const Point& p) const {
return C(x) * C(p.x) + C(y) * C(p.y);
}
constexpr C cross(const Point& p) const {
return C(x) * C(p.y) - C(y) * C(p.x);
}
constexpr C operator*(const Point& p) const { return dot(p); }
constexpr C operator^(const Point& p) const { return cross(p); }
constexpr C norm2() const { return dot(*this); }
Real norm() const {
return std::hypot(Real(x), Real(y));
}
constexpr C dist2(const Point& p) const {
C dx = C(x) - C(p.x), dy = C(y) - C(p.y);
return dx * dx + dy * dy;
}
Real dist(const Point& p) const {
return std::hypot(Real(x) - Real(p.x), Real(y) - Real(p.y));
}
constexpr C orient(const Point& b, const Point& c) const {
return (C(b.x) - C(x)) * (C(c.y) - C(y)) - (C(b.y) - C(y)) * (C(c.x) - C(x));
}
constexpr int ccw(const Point& b, const Point& c) const { C v = orient(b, c); return (v > 0) - (v < 0); }
constexpr Point rotated90(int k = 1) const {
k %= 4;
if (k < 0) k += 4;
if (k == 1) return {T(-C(y)), x};
if (k == 2) return {T(-C(x)), T(-C(y))};
if (k == 3) return {y, T(-C(x))};
return *this;
}
constexpr void rot90(int k = 1) { *this = rotated90(k); }
Real arg() const {
return std::atan2(Real(y), Real(x));
}
Point rotated(T angle) const requires std::is_floating_point_v<T> {
T c = std::cos(angle), s = std::sin(angle);
return {T(C(x) * C(c) - C(y) * C(s)), T(C(x) * C(s) + C(y) * C(c))};
}
void rot(T angle) requires std::is_floating_point_v<T> { *this = rotated(angle); }
Point normalized() const requires std::is_floating_point_v<T> {
#ifndef SKIP_RUNTIME_CHECKS
if (!std::isfinite(x) || !std::isfinite(y)) throw std::domain_error("nonfinite vector");
#endif
T m = std::max(std::abs(x), std::abs(y));
if (m == 0) throw std::domain_error("normalize zero vector");
T ax = x / m, ay = y / m, length = std::hypot(ax, ay);
return {ax / length, ay / length};
}
bool almost_equal(const Point& p, Epsilon eps = {}) const requires std::is_floating_point_v<T> {
return std::abs(static_cast<long double>(x) - p.x) <= eps.tolerance(std::max(std::abs(static_cast<long double>(x)), std::abs(static_cast<long double>(p.x))))
&& std::abs(static_cast<long double>(y) - p.y) <= eps.tolerance(std::max(std::abs(static_cast<long double>(y)), std::abs(static_cast<long double>(p.y))));
}
template<class U, class D = DefaultCalc<U>> constexpr Point<U, D> cast() const {
return {static_cast<U>(x), static_cast<U>(y)};
}
static bool arg_cmp(const Point& a, const Point& b) {
bool az = a.x == 0 && a.y == 0, bz = b.x == 0 && b.y == 0;
if (az || bz) return az && !bz;
bool ah = a.y < 0 || (a.y == 0 && a.x < 0), bh = b.y < 0 || (b.y == 0 && b.x < 0);
if (ah != bh) return ah < bh;
if constexpr (std::is_integral_v<T>) {
C turn = C(a.x) * C(b.y) - C(a.y) * C(b.x);
if (turn != 0) return turn > 0;
return a.norm2() < b.norm2();
} else {
// 固定した偏角キーで比較し、近い角度の丸めでも推移律を保つ。
Real aa = std::atan2(a.y, a.x), ab = std::atan2(b.y, b.x);
if (aa < 0) aa += 2 * std::numbers::pi_v<Real>;
if (ab < 0) ab += 2 * std::numbers::pi_v<Real>;
if (aa != ab) return aa < ab;
Real na = std::hypot(a.x, a.y), nb = std::hypot(b.x, b.y);
if (na != nb) return na < nb;
return std::max(std::abs(a.x), std::abs(a.y)) < std::max(std::abs(b.x), std::abs(b.y));
}
}
friend std::ostream& operator<<(std::ostream& out, const Point& p) { return out << '(' << p.x << ',' << p.y << ')'; }
};
using PointI = Point<std::int64_t>;
using PointD = Point<double>;
using PointLD = Point<long double>;
using RealPoint = PointLD;
}
#endif
#ifndef SIRKIT_GEO_POINT_FUNCTIONS_DEFINED
#define SIRKIT_GEO_POINT_FUNCTIONS_DEFINED
namespace geo {
template<class T, class C> int predicate_sign(C value, C scale, Epsilon eps = {}) {
if constexpr (std::is_integral_v<T>) return (value > 0) - (value < 0);
else {
long double tolerance = eps.tolerance(static_cast<long double>(scale));
return (value > tolerance) - (value < -tolerance);
}
}
template<class T, class C> int orientation(const Point<T, C>& a, const Point<T, C>& b, const Point<T, C>& c, Epsilon eps = {}) {
C ux = C(b.x) - C(a.x), uy = C(b.y) - C(a.y), vx = C(c.x) - C(a.x), vy = C(c.y) - C(a.y);
C p = ux * vy, q = uy * vx;
if constexpr (std::is_integral_v<T>) return (p > q) - (p < q);
else return predicate_sign<T, C>(p - q, std::abs(p) + std::abs(q), eps);
}
template<class T, class C> RealPoint to_real(const Point<T, C>& p) { return p.template cast<long double>(); }
template<class T, class C> typename Point<T, C>::Real distance(const Point<T, C>& p, const Point<T, C>& q) { return p.dist(q); }
}
#endif
#ifndef SIRKIT_GEO_LOCATION_DEFINED
#define SIRKIT_GEO_LOCATION_DEFINED
namespace geo {
enum class Location { Outside, Boundary, Inside };
}
#endif
#ifndef SIRKIT_GEO_CONVEX_POLYGON_LOCATOR_DEFINED
#define SIRKIT_GEO_CONVEX_POLYGON_LOCATOR_DEFINED
namespace geo {
template <std::signed_integral T = std::int64_t, class C = DefaultCalc<T>>
requires(std::numeric_limits<C>::is_integer && std::numeric_limits<C>::is_signed)
class ConvexPolygonLocator
{
using P = Point<T, C>;
public:
explicit ConvexPolygonLocator(std::vector<P> vertices = {})
: vertices_(std::move(vertices))
{
vertices_.erase(std::unique(vertices_.begin(), vertices_.end()), vertices_.end());
if (vertices_.size() > 1 && vertices_.front() == vertices_.back())
{
vertices_.pop_back();
}
if (vertices_.size() < 2)
{
return;
}
auto pivot = std::min_element(vertices_.begin(), vertices_.end());
std::rotate(vertices_.begin(), pivot, vertices_.end());
const int direction = orientation(vertices_.front(), vertices_[1], vertices_.back());
if (direction == 0)
{
const auto last = *std::max_element(vertices_.begin(), vertices_.end());
vertices_.resize(2);
vertices_[1] = last;
return;
}
if (direction < 0)
{
std::reverse(vertices_.begin() + 1, vertices_.end());
}
std::size_t kept = 1;
for (std::size_t i = 1; i < vertices_.size(); ++i)
{
const auto vertex = vertices_[i];
while (kept >= 2 && orientation(vertices_[kept - 2], vertices_[kept - 1], vertex) == 0)
{
--kept;
}
vertices_[kept++] = vertex;
}
if (orientation(vertices_[kept - 2], vertices_[kept - 1], vertices_[0]) == 0)
{
--kept;
}
vertices_.resize(kept);
}
[[nodiscard]] Location locate(const P &point) const
{
const auto n = vertices_.size();
if (n == 0)
{
return Location::Outside;
}
if (n == 1)
{
return point == vertices_[0] ? Location::Boundary : Location::Outside;
}
const auto &origin = vertices_[0];
const int low = orientation(origin, vertices_[1], point);
if (n == 2)
{
return low == 0 ? OnRaySegment(vertices_[1], point) : Location::Outside;
}
const int high = orientation(origin, vertices_.back(), point);
if (low < 0 || high > 0)
{
return Location::Outside;
}
if (low == 0)
{
return OnRaySegment(vertices_[1], point);
}
if (high == 0)
{
return OnRaySegment(vertices_.back(), point);
}
std::size_t left = 1, right = n - 1;
while (right - left > 1)
{
const std::size_t middle = left + (right - left) / 2;
if (orientation(origin, vertices_[middle], point) >= 0)
{
left = middle;
}
else
{
right = middle;
}
}
const int side = orientation(vertices_[left], vertices_[right], point);
if (side < 0)
{
return Location::Outside;
}
return side == 0 ? Location::Boundary : Location::Inside;
}
private:
[[nodiscard]] Location OnRaySegment(const P &end, const P &point) const
{
return vertices_[0] <= point && point <= end ? Location::Boundary : Location::Outside;
}
std::vector<P> vertices_;
};
}
#endif
} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1