#define SKIP_RUNTIME_CHECKS // Verify: https://yukicoder.me/problems/no/172 // Library: Geometry/geometory.cpp // SPDX-License-Identifier: CC0-1.0 // ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/geometry_point.md // ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/geometry_orientation.md // ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/geometry_segment_intersection.md // ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/geometry_point_segment_distance.md // ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/geometry_area.md // ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/geometry_point_location.md // ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/convex_hull.md // ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/geometry_circle_intersection.md // // API一覧 // [geo::Epsilon] // Epsilon{abs,rel}: 非負有限の絶対・相対許容幅(既定は各1e-12L)。 // tolerance(scale): abs + rel * abs(scale) を返す。O(1)。 // // [geo::Point] // Point>{x,y}: 符号付き整数/浮動小数点の集成体。座標・座標演算はT、差・積・和はCに収まる有限入力。 // DefaultCalc: 整数は対応環境で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() は座標型変換。arg_cmp は零点を先頭に偏角・距離順。O(1)。 // 浮動 arg_cmp は丸めた偏角が等しければ距離順。ostream は (x,y) を出力する。O(1)。 // // [geo::点の関数] // 点の関数。座標は有限、整数の差・積は C に収まる入力を扱う。 // predicate_sign(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::Line / geo::Segment] // Segment{a,b} は閉線分(零長可)、Line{a,b} は相異なる2点で表す直線。 // // [geo::on_segment] // on_segment(p,s,eps): 閉線分上(端点を含む)なら true。整数では厳密。O(1)。 // // [geo::intersects] // intersects(s,t,eps): 閉線分同士が端点・重なりを含め交わるか。O(1)。 // // [geo::直線・線分の交差型] // LineIntersectionKind: None/Point/Coincident。LineIntersection{kind,point}: 交点をoptionalで所有。 // SegmentIntersectionKind: None/Point/Overlap。SegmentIntersection{kind,points}: 近似交点、重なりは辞書順の両端点を所有。 // // [geo::直線・線分の関数] // 点・直線・閉線分の関数。交点・射影・距離は long double で近似する。 // projection(p,l): long double 変換後も非零長の直線 l 上への射影。O(1)。 // reflection(p,l): 直線 l に関して対称な点。projection と同じ前提。O(1)。 // closest_point(p,s): 閉線分上の最近点。long double 変換後の零長線分は a を返す。O(1)。 // distance(p,l): 点と非零長直線の距離。O(1)。 // distance(p,s): 点と閉線分の距離(零長可)。O(1)。 // distance(s,t,eps): 閉線分間距離。intersects が真なら0。O(1)。 // intersection(l,m,eps): 非零長直線の交差種別と近似交点。O(1)。 // intersection(s,t,eps): 閉線分の交点、または元の座標で辞書順に選んだ重なりの両端点。O(1)。 // // [geo::Location] // Location: containsの戻り値。Outside/Boundary/Insideは外部/境界/内部。 // // [多角形・三角形] // 多角形は vector>。先頭点の重複による閉包は不要。 // signed_area2(poly): 符号付き面積の2倍を C で返す。反時計回りが正。O(N)、空は0。 // area(poly): 面積の絶対値を long double で返す。O(N)。 // signed_triangle_area2(a,b,c): 三角形の符号付き面積の2倍をCで返す。差・積・減算がCに収まる入力。O(1)。 // triangle_area(a,b,c): 三角形の面積をlong doubleで返す。退化三角形は0。配列確保なし。O(1)。 // perimeter(poly): 閉じた辺の総延長。0/1点は0、2点は往復分。O(N)。 // contains(poly,p,eps): 単純多角形の内外・境界を巻き数で返す。0点は外、1/2点は境界のみ。O(N)。 // convex_hull(points,eps): 完全一致を除き、辞書順最小点から反時計回りの凸包。一直線は両端のみ。O(N log N)。 // convex_hull_sorted(points,eps): 辞書順整列済みのgeo::Pointから反時計回りの凸包を返す。重複可。O(N)。 // centroid(poly,eps): 単純多角形の面積重心。3点未満または面積0なら nullopt。O(N)。 // convex_cut(poly,l,eps): 凸多角形と有向非零長直線の左側(境界含む)との共通部分。O(N)。 // // [geo::円の型] // CircleIntersectionKind: None/Tangent/TwoPoints/Coincident。CircleIntersection{kind,points}: 近似交点を所有。 // 一致する正半径円には交点を格納しない。半径0同士の同一点はTangentと1交点。 // Circle{center,radius}: 有限の中心と非負の有限半径。半径0は点。 // // [円の関数] // 円周・円盤の関数。eps は絶対・相対許容幅、交点は RealPoint。 // circumcircle(a,b,c,eps): 3点を通る円。一直線・重複点なら nullopt。O(1)。 // validate(c): 中心・半径が有限かつ半径非負かを検査し、不正なら domain_error。省略設定でも有効。O(1)。 // contains(c,p,eps): 円盤の外・円周上・内を距離で判定する。O(1)。 // intersection(c,l,eps): 円周と非零長直線の交点を直線の向き順に0/1/2点返す。O(1)。 // intersection(c,s,eps): 円周と閉線分の交点を線分の向き順に返す。零長線分も可。O(1)。 // intersection(a,b,eps): 円周同士の交差種別と交点。半径0同士の同一点は Tangent。O(1)。 // circle_intersection_kind(a,b,eps): 円周の交差種別。geo::intersection と同じ判定で交点を確保しない。O(1)。 // SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。 #include #include #include #include #include #include #include #include #include #include #include #include #include #include // 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 using DefaultCalc = std::conditional_t, __int128_t, T>; #else template using DefaultCalc = std::conditional_t, std::int64_t, T>; #endif template> struct Point { static_assert((std::is_integral_v && std::is_signed_v) || std::is_floating_point_v); using Value = T; using Calc = C; using Real = std::conditional_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 requires std::is_integral_v Point operator*(U) const = delete; constexpr Point& operator*=(T k) { return *this = *this * k; } template requires std::is_integral_v Point& operator*=(U) = delete; friend constexpr Point operator*(T k, const Point& p) { return p * k; } template requires std::is_integral_v friend Point operator*(U, const Point&) = delete; Point operator/(T k) const requires std::is_floating_point_v { 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 { 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 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 { *this = rotated(angle); } Point normalized() const requires std::is_floating_point_v { #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 { return std::abs(static_cast(x) - p.x) <= eps.tolerance(std::max(std::abs(static_cast(x)), std::abs(static_cast(p.x)))) && std::abs(static_cast(y) - p.y) <= eps.tolerance(std::max(std::abs(static_cast(y)), std::abs(static_cast(p.y)))); } template> constexpr Point cast() const { return {static_cast(x), static_cast(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) { 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; if (ab < 0) ab += 2 * std::numbers::pi_v; 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; using PointD = Point; using PointLD = Point; using RealPoint = PointLD; } #endif #ifndef SIRKIT_GEO_POINT_FUNCTIONS_DEFINED #define SIRKIT_GEO_POINT_FUNCTIONS_DEFINED namespace geo { template int predicate_sign(C value, C scale, Epsilon eps = {}) { if constexpr (std::is_integral_v) return (value > 0) - (value < 0); else { long double tolerance = eps.tolerance(static_cast(scale)); return (value > tolerance) - (value < -tolerance); } } template int orientation(const Point& a, const Point& b, const Point& 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) return (p > q) - (p < q); else return predicate_sign(p - q, std::abs(p) + std::abs(q), eps); } template RealPoint to_real(const Point& p) { return p.template cast(); } template typename Point::Real distance(const Point& p, const Point& q) { return p.dist(q); } } #endif #ifndef SIRKIT_GEO_LINEAR_TYPES_DEFINED #define SIRKIT_GEO_LINEAR_TYPES_DEFINED namespace geo { template> struct Segment { Point a, b; }; template> struct Line { Point a, b; }; } #endif #ifndef SIRKIT_GEO_ON_SEGMENT_DEFINED #define SIRKIT_GEO_ON_SEGMENT_DEFINED namespace geo { template bool on_segment(const Point& p, const Segment& s, Epsilon eps = {}) { if (orientation(s.a, s.b, p, eps) != 0) return false; C x = (C(p.x) - C(s.a.x)) * (C(p.x) - C(s.b.x)); C y = (C(p.y) - C(s.a.y)) * (C(p.y) - C(s.b.y)); if constexpr (std::is_integral_v) return x + y <= 0; else return predicate_sign(x + y, std::abs(x) + std::abs(y), eps) <= 0; } } #endif #ifndef SIRKIT_GEO_SEGMENT_FLOAT_DEFINED #define SIRKIT_GEO_SEGMENT_FLOAT_DEFINED namespace detail { template inline constexpr bool kExactFloatingSegment = std::is_floating_point_v && std::numeric_limits::radix == 2; struct SegmentScaledMagnitude { long double fraction = 0; int exponent = 0; int sign = 0; }; // 二進浮動小数点の積和を、共通の二進桁に揃えて加減算する。 template class SegmentDeterminant { static constexpr int kFirstBit = 2 * (std::numeric_limits::min_exponent - std::numeric_limits::digits) - std::numeric_limits::digits - 64; static constexpr int kWords = (2 * std::numeric_limits::max_exponent + 8 - kFirstBit + 31) / 32; using Words = std::array; Words positive_{}, negative_{}; int first_ = kWords; int last_ = -1; void accumulate(Words& words, long double value, int scale) { int exponent; long double fraction = std::frexp(value, &exponent); for (int bit = exponent + scale - kFirstBit - 32; fraction != 0; bit -= 32) { fraction = std::ldexp(fraction, 32); const auto chunk = static_cast(fraction); fraction -= chunk; if (chunk == 0) continue; int word = bit / 32; first_ = std::min(first_, word); std::uint64_t carry = std::uint64_t{chunk} << (bit % 32); do { const auto sum = std::uint64_t{words[word]} + static_cast(carry); words[word] = static_cast(sum); carry = (carry >> 32) + (sum >> 32); last_ = std::max(last_, word++); } while (carry != 0); } } void add_product(C x, C y, bool subtract) { if (x == 0 || y == 0) return; int x_scale, y_scale; const long double a = std::frexp(static_cast(x), &x_scale); const long double b = std::frexp(static_cast(y), &y_scale); const long double high = a * b; // 仮数同士の積は通常範囲にあり、FMAで丸め前の残差を取り出せる。 const long double low = std::fma(a, b, -high); const auto add_term = [&](long double term) { auto& words = (term < 0) != subtract ? negative_ : positive_; accumulate(words, std::abs(term), x_scale + y_scale); }; add_term(high); add_term(low); } SegmentScaledMagnitude value(long double tolerance) { int top = last_; while (top >= first_ && positive_[top] == negative_[top]) --top; if (top < first_) return {}; const bool negative = positive_[top] < negative_[top]; auto& magnitude = negative ? negative_ : positive_; auto& other = negative ? positive_ : negative_; std::uint64_t borrow = 0; for (int i = first_; i <= top; ++i) { const std::uint64_t minuend = magnitude[i]; const std::uint64_t subtrahend = std::uint64_t{other[i]} + borrow; magnitude[i] = static_cast(minuend - subtrahend); borrow = minuend < subtrahend; } while (magnitude[top] == 0) --top; if (tolerance > 0) { if (!std::isfinite(tolerance)) return {}; int exponent; std::frexp(tolerance, &exponent); int top_exponent; std::frexp(static_cast(magnitude[top]), &top_exponent); const int magnitude_exponent = kFirstBit + top * 32 + top_exponent; if (magnitude_exponent < exponent) return {}; if (magnitude_exponent == exponent) { other.fill(0); accumulate(other, tolerance, 0); int i = top; while (i >= first_ && magnitude[i] == other[i]) --i; if (i < first_ || magnitude[i] < other[i]) return {}; } } // 座標を近似する際は先頭の仮数だけを使用し、指数は別に保持する。 constexpr int kLeadingWords = (std::numeric_limits::digits + 31) / 32; const int bottom = std::max(first_, top - kLeadingWords); long double leading = magnitude[top]; for (int i = top - 1; i >= bottom; --i) leading = std::ldexp(leading, 32) + magnitude[i]; int exponent; const long double fraction = std::frexp(leading, &exponent); return {fraction, exponent + kFirstBit + bottom * 32, negative ? -1 : 1}; } public: template SegmentScaledMagnitude orientation(const geo::Point& a, const geo::Point& b, const geo::Point& c, long double tolerance = 0) { const C ax = C(a.x), ay = C(a.y), bx = C(b.x), by = C(b.y), cx = C(c.x), cy = C(c.y); add_product(bx, cy, false); add_product(bx, ay, true); add_product(ax, cy, true); add_product(by, cx, true); add_product(by, ax, false); add_product(ay, cx, false); return value(tolerance); } }; template int floating_segment_side(const geo::Point& a, const geo::Point& b, const geo::Point& c, geo::Epsilon eps) { const C p = (C(b.x) - C(a.x)) * (C(c.y) - C(a.y)); const C q = (C(b.y) - C(a.y)) * (C(c.x) - C(a.x)); const long double determinant = static_cast(p) - static_cast(q); const long double scale = std::abs(static_cast(p)) + std::abs(static_cast(q)); const long double tolerance = std::is_integral_v ? 0 : eps.rel == 0 ? eps.abs : eps.tolerance(scale); // 差と積の丸め、非正規数の絶対誤差を含む保守的な幅。 const long double error = 16 * std::numeric_limits::epsilon() * scale + 8 * static_cast(std::numeric_limits::min()); if (std::abs(std::abs(determinant) - tolerance) > error) return (determinant > tolerance) - (determinant < -tolerance); return SegmentDeterminant{}.orientation(a, b, c, tolerance).sign; } template std::array floating_segment_sides(const geo::Segment& s, const geo::Segment& t, geo::Epsilon eps) { return {floating_segment_side(t.a, t.b, s.a, eps), floating_segment_side(t.a, t.b, s.b, eps), floating_segment_side(s.a, s.b, t.a, eps), floating_segment_side(s.a, s.b, t.b, eps)}; } inline bool segment_proper_crossing(const std::array& sides) { return sides[0] * sides[1] < 0 && sides[2] * sides[3] < 0; } template bool floating_segment_endpoint(const geo::Point& p, const geo::Segment& s, int side, geo::Epsilon eps) { if (side != 0) return false; if (std::is_integral_v || (eps.abs == 0 && eps.rel == 0)) { return std::min(s.a.x, s.b.x) <= p.x && p.x <= std::max(s.a.x, s.b.x) && std::min(s.a.y, s.b.y) <= p.y && p.y <= std::max(s.a.y, s.b.y); } const C x = (C(p.x) - C(s.a.x)) * (C(p.x) - C(s.b.x)); const C y = (C(p.y) - C(s.a.y)) * (C(p.y) - C(s.b.y)); return geo::predicate_sign(x + y, std::abs(x) + std::abs(y), eps) <= 0; } template std::array floating_segment_contacts(const geo::Segment& s, const geo::Segment& t, const std::array& sides, geo::Epsilon eps) { return {floating_segment_endpoint(s.a, t, sides[0], eps), floating_segment_endpoint(s.b, t, sides[1], eps), floating_segment_endpoint(t.a, s, sides[2], eps), floating_segment_endpoint(t.b, s, sides[3], eps)}; } template SegmentScaledMagnitude floating_segment_magnitude(const geo::Point& a, const geo::Point& b, const geo::Point& c) { const auto convert = [](T value) { return static_cast(C(value)); }; const long double ux = convert(b.x) - convert(a.x), uy = convert(b.y) - convert(a.y); const long double vx = convert(c.x) - convert(a.x), vy = convert(c.y) - convert(a.y); const long double p = ux * vy, q = uy * vx; const long double magnitude = std::abs(p - q); const long double scale = std::abs(p) + std::abs(q); // 交点の比に使う仮数は、桁落ちが小さい場合だけ通常演算から得る。 if (magnitude > scale * 0x1p-12L && scale >= std::numeric_limits::min()) { int exponent; const long double fraction = std::frexp(magnitude, &exponent); return {fraction, exponent, 1}; } return SegmentDeterminant{}.orientation(a, b, c); } template geo::RealPoint floating_segment_crossing(const geo::Segment& s, const geo::Segment& t) { const auto a = floating_segment_magnitude(t.a, t.b, s.a); const auto b = floating_segment_magnitude(t.a, t.b, s.b); // 端点の向きが異符号なので、媒介変数の分母は絶対値の和になる。 const bool reverse = a.exponent > b.exponent || (a.exponent == b.exponent && a.fraction > b.fraction); const auto& near = reverse ? b : a; const auto& far = reverse ? a : b; const long double scaled_near = std::ldexp(near.fraction, near.exponent - far.exponent); const long double ratio = scaled_near / (far.fraction + scaled_near); const auto& start = reverse ? s.b : s.a; const auto& end = reverse ? s.a : s.b; return {std::lerp(static_cast(C(start.x)), static_cast(C(end.x)), ratio), std::lerp(static_cast(C(start.y)), static_cast(C(end.y)), ratio)}; } } #endif #ifndef SIRKIT_GEO_SEGMENT_PREDICATES_DEFINED #define SIRKIT_GEO_SEGMENT_PREDICATES_DEFINED namespace geo { template bool intersects(const Segment& s, const Segment& t, Epsilon eps = {}) { if constexpr (::sirkit::detail::kExactFloatingSegment) { const auto sides = ::sirkit::detail::floating_segment_sides(s, t, eps); if (::sirkit::detail::segment_proper_crossing(sides)) return true; const auto contacts = ::sirkit::detail::floating_segment_contacts(s, t, sides, eps); return std::ranges::any_of(contacts, [](bool contact) { return contact; }); } else if constexpr (std::is_integral_v) { const int a = orientation(s.a, s.b, t.a, eps), b = orientation(s.a, s.b, t.b, eps); if (a * b > 0) return false; // 整数計算で共線と分かった場合は、変化する1軸だけを調べる。 auto in_box = [](const Point& p, const Segment& line) { if constexpr (std::numeric_limits::is_integer) { if (line.a.x != line.b.x) return std::min(line.a.x, line.b.x) <= p.x && p.x <= std::max(line.a.x, line.b.x); if (line.a.y != line.b.y) return std::min(line.a.y, line.b.y) <= p.y && p.y <= std::max(line.a.y, line.b.y); return p == line.a; } return std::min(line.a.x, line.b.x) <= p.x && p.x <= std::max(line.a.x, line.b.x) && std::min(line.a.y, line.b.y) <= p.y && p.y <= std::max(line.a.y, line.b.y); }; if (a == 0) { if (b != 0) return in_box(t.a, s); if (s.a == s.b) return orientation(t.a, t.b, s.a, eps) == 0 && in_box(s.a, t); if constexpr (std::numeric_limits::is_integer) { if (s.a.x != s.b.x) return std::max(s.a.x, s.b.x) >= std::min(t.a.x, t.b.x) && std::max(t.a.x, t.b.x) >= std::min(s.a.x, s.b.x); return std::max(s.a.y, s.b.y) >= std::min(t.a.y, t.b.y) && std::max(t.a.y, t.b.y) >= std::min(s.a.y, s.b.y); } return std::max(s.a.x, s.b.x) >= std::min(t.a.x, t.b.x) && std::max(t.a.x, t.b.x) >= std::min(s.a.x, s.b.x) && std::max(s.a.y, s.b.y) >= std::min(t.a.y, t.b.y) && std::max(t.a.y, t.b.y) >= std::min(s.a.y, s.b.y); } if (b == 0) return in_box(t.b, s); const int c = orientation(t.a, t.b, s.a, eps), d = orientation(t.a, t.b, s.b, eps); return c * d <= 0; } else { const int a = orientation(s.a, s.b, t.a, eps), b = orientation(s.a, s.b, t.b, eps); const int c = orientation(t.a, t.b, s.a, eps), d = orientation(t.a, t.b, s.b, eps); if (a == 0 && on_segment(t.a, s, eps)) return true; if (b == 0 && on_segment(t.b, s, eps)) return true; if (c == 0 && on_segment(s.a, t, eps)) return true; if (d == 0 && on_segment(s.b, t, eps)) return true; return a * b < 0 && c * d < 0; } } } #endif #ifndef SIRKIT_GEO_LINEAR_RESULTS_DEFINED #define SIRKIT_GEO_LINEAR_RESULTS_DEFINED namespace geo { enum class LineIntersectionKind { None, Point, Coincident }; enum class SegmentIntersectionKind { None, Point, Overlap }; struct LineIntersection { LineIntersectionKind kind = LineIntersectionKind::None; std::optional point; }; struct SegmentIntersection { SegmentIntersectionKind kind = SegmentIntersectionKind::None; std::vector points; }; } #endif #ifndef SIRKIT_GEO_LINEAR_DEFINED #define SIRKIT_GEO_LINEAR_DEFINED namespace geo { template RealPoint projection(const Point& p, const Line& l) { RealPoint a = to_real(l.a), b = to_real(l.b), q = to_real(p); RealPoint d = b - a; if (d.x == 0 && d.y == 0) throw std::domain_error("degenerate line"); RealPoint u = d.normalized(); return a + u * ((q - a).dot(u)); } template RealPoint reflection(const Point& p, const Line& l) { RealPoint q = projection(p, l); return q + (q - to_real(p)); } template RealPoint closest_point(const Point& p, const Segment& s) { RealPoint a = to_real(s.a), b = to_real(s.b), q = to_real(p), d = b - a; if (d.x == 0 && d.y == 0) return a; RealPoint u = d.normalized(); long double along = (q - a).dot(u); if (along <= 0) return a; if ((q - b).dot(u) >= 0) return b; return a + u * along; } template long double distance(const Point& p, const Line& l) { RealPoint a = to_real(l.a), b = to_real(l.b), q = to_real(p), d = b - a; if (d.x == 0 && d.y == 0) throw std::domain_error("degenerate line"); return std::abs((q - a).cross(d.normalized())); } template long double distance(const Point& p, const Segment& s) { RealPoint a = to_real(s.a), b = to_real(s.b), q = to_real(p), d = b - a; if (d.x == 0 && d.y == 0) return q.dist(a); // 整数の差の二乗和が表せる場合は、方向長を直接計算する。 RealPoint u; if constexpr (std::is_integral_v && sizeof(T) <= 8 && std::numeric_limits::max_exponent > 2 * (std::numeric_limits::digits + 1) + 1) { const long double length = std::sqrt(d.x * d.x + d.y * d.y); u = {d.x / length, d.y / length}; } else u = d.normalized(); const RealPoint offset = q - a; if (offset.dot(u) <= 0) return q.dist(a); if ((q - b).dot(u) >= 0) return q.dist(b); return std::abs(offset.cross(u)); } template long double distance(const Segment& s, const Segment& t, Epsilon eps = {}) { if (intersects(s, t, eps)) return 0; return std::min({distance(s.a, t), distance(s.b, t), distance(t.a, s), distance(t.b, s)}); } template LineIntersection intersection(const Line& l, const Line& m, Epsilon eps = {}) { if (l.a == l.b || m.a == m.b) throw std::domain_error("degenerate line"); C ux = C(l.b.x) - C(l.a.x), uy = C(l.b.y) - C(l.a.y); C vx = C(m.b.x) - C(m.a.x), vy = C(m.b.y) - C(m.a.y); C p = ux * vy, q = uy * vx, determinant = p - q; int sign; if constexpr (std::is_integral_v) sign = (determinant > 0) - (determinant < 0); else sign = predicate_sign(determinant, std::abs(p) + std::abs(q), eps); if (sign == 0) { if (orientation(l.a, l.b, m.a, eps) == 0) return {LineIntersectionKind::Coincident, std::nullopt}; return {}; } C wx = C(m.a.x) - C(l.a.x), wy = C(m.a.y) - C(l.a.y); long double t = static_cast(wx * vy - wy * vx) / static_cast(determinant); return {LineIntersectionKind::Point, RealPoint{static_cast(l.a.x) + t * static_cast(ux), static_cast(l.a.y) + t * static_cast(uy)}}; } template SegmentIntersection intersection(const Segment& s, const Segment& t, Epsilon eps = {}) { const std::array endpoints{s.a, s.b, t.a, t.b}; std::array sides; std::array contacts; if constexpr (::sirkit::detail::kExactFloatingSegment) { sides = ::sirkit::detail::floating_segment_sides(s, t, eps); contacts = ::sirkit::detail::floating_segment_contacts(s, t, sides, eps); } else { contacts = {on_segment(s.a, t, eps), on_segment(s.b, t, eps), on_segment(t.a, s, eps), on_segment(t.b, s, eps)}; } std::array, 4> candidates; std::size_t n = 0; for (std::size_t i = 0; i < endpoints.size(); ++i) if (contacts[i]) candidates[n++] = endpoints[i]; if (n != 0) { auto ends = std::minmax_element(candidates.begin(), candidates.begin() + static_cast(n)); if (*ends.first == *ends.second) return {SegmentIntersectionKind::Point, {to_real(*ends.first)}}; return {SegmentIntersectionKind::Overlap, {to_real(*ends.first), to_real(*ends.second)}}; } if constexpr (::sirkit::detail::kExactFloatingSegment) { if (!::sirkit::detail::segment_proper_crossing(sides)) return {}; return {SegmentIntersectionKind::Point, {::sirkit::detail::floating_segment_crossing(s, t)}}; } else { sides = {orientation(t.a, t.b, s.a, eps), orientation(t.a, t.b, s.b, eps), orientation(s.a, s.b, t.a, eps), orientation(s.a, s.b, t.b, eps)}; if (!::sirkit::detail::segment_proper_crossing(sides)) return {}; C ux = C(s.b.x) - C(s.a.x), uy = C(s.b.y) - C(s.a.y); C vx = C(t.b.x) - C(t.a.x), vy = C(t.b.y) - C(t.a.y); C wx = C(t.a.x) - C(s.a.x), wy = C(t.a.y) - C(s.a.y); C determinant = ux * vy - uy * vx; if constexpr (!std::numeric_limits::is_integer) { if (determinant == 0) return {}; } long double ratio = static_cast(wx * vy - wy * vx) / static_cast(determinant); return {SegmentIntersectionKind::Point, {{static_cast(s.a.x) + ratio * static_cast(ux), static_cast(s.a.y) + ratio * static_cast(uy)}}}; } } } #endif #ifndef SIRKIT_GEO_LOCATION_DEFINED #define SIRKIT_GEO_LOCATION_DEFINED namespace geo { enum class Location { Outside, Boundary, Inside }; } #endif #ifndef SIRKIT_GEO_POLYGON_DEFINED #define SIRKIT_GEO_POLYGON_DEFINED namespace geo { template C signed_area2(const std::vector>& poly) { if (poly.size() < 3) return C{0}; const C origin_x = C(poly[0].x), origin_y = C(poly[0].y); // 直前の頂点の座標差を次の三角形にも使う。 C previous_x = C(poly[1].x) - origin_x, previous_y = C(poly[1].y) - origin_y; C result = 0; const auto* it = poly.data() + 2; const auto* end = poly.data() + poly.size(); for (; it != end; ++it) { const C x = C(it->x) - origin_x, y = C(it->y) - origin_y; result += previous_x * y - previous_y * x; previous_x = x; previous_y = y; } return result; } template long double area(const std::vector>& poly) { return std::abs(static_cast(signed_area2(poly))) / 2; } template long double perimeter(const std::vector>& poly) { if (poly.size() < 2) return 0; long double result = 0; for (std::size_t i = 0; i < poly.size(); ++i) result += poly[i].dist(poly[i + 1 == poly.size() ? 0 : i + 1]); return result; } template Location contains(const std::vector>& poly, const Point& p, Epsilon eps = {}) { if (poly.empty()) return Location::Outside; if (poly.size() == 1) return on_segment(p, Segment{poly[0], poly[0]}, eps) ? Location::Boundary : Location::Outside; std::int64_t winding = 0; for (std::size_t i = 0; i < poly.size(); ++i) { const auto& a = poly[i]; const auto& b = poly[i + 1 == poly.size() ? 0 : i + 1]; if constexpr (std::is_integral_v) { if ((a.y < p.y && b.y < p.y) || (a.y > p.y && b.y > p.y)) continue; } int side = orientation(a, b, p, eps); if (side == 0) { if constexpr (std::is_integral_v) { // 上の走査で p.y が辺の y の範囲内と確認済み。 if (std::min(a.x, b.x) <= p.x && p.x <= std::max(a.x, b.x)) return Location::Boundary; } else if (on_segment(p, Segment{a, b}, eps)) return Location::Boundary; } if (a.y <= p.y && p.y < b.y && side > 0) ++winding; if (b.y <= p.y && p.y < a.y && side < 0) --winding; } return winding != 0 ? Location::Inside : Location::Outside; } } #ifndef SIRKIT_GEO_CONVEX_HULL_IMPL_DEFINED #define SIRKIT_GEO_CONVEX_HULL_IMPL_DEFINED namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ { inline bool convex_hull_combined_radix_counts(std::size_t keys, unsigned active) noexcept { return keys >= 16384 && keys <= std::numeric_limits::max() && active >= 6; } inline std::size_t convex_hull_reserve_size(std::size_t points, std::size_t capacity) { if (points >= capacity) throw std::length_error("geometry hull capacity"); return points + 1; } template std::vector> convex_hull_impl(std::vector> points, geo::Epsilon eps) { constexpr bool narrow_integer = std::is_integral_v && sizeof(T) <= 8 && std::numeric_limits::is_integer && std::numeric_limits::digits >= 63; bool narrow = false; bool radix_unique = false; if constexpr (narrow_integer) { if (points.size() <= 1) return points; T min_x = points.front().x, max_x = min_x; T min_y = points.front().y, max_y = min_y; [[maybe_unused]] bool ordered = true; for (std::size_t i = 1; i < points.size(); ++i) { const auto& p = points[i]; min_x = std::min(min_x, p.x); max_x = std::max(max_x, p.x); min_y = std::min(min_y, p.y); max_y = std::max(max_y, p.y); #ifndef SKIP_RUNTIME_CHECKS if constexpr (Sorted) { if (p < points[i - 1]) throw std::invalid_argument("convex_hull_sorted: points are not sorted"); } #endif if constexpr (!Sorted) ordered = ordered && !(p < points[i - 1]); } const auto span_x = std::uint64_t(max_x) - std::uint64_t(min_x); const auto span_y = std::uint64_t(max_y) - std::uint64_t(min_y); constexpr auto maximum = std::uint64_t(std::numeric_limits::max()); // 積を別々に比較するため、外積の減算は行わない。 narrow = span_x <= maximum && span_y <= maximum && (span_y == 0 || span_x <= maximum / span_y); if constexpr (!Sorted) { if (!ordered) { if (points.size() >= 2048 && span_x <= std::numeric_limits::max() && span_y <= std::numeric_limits::max()) { // 領域を先に確保し、キー生成中の容量判定を省く。 std::vector keys(points.size()); std::uint64_t varying = 0; const auto first = ((std::uint64_t(points.front().x) - std::uint64_t(min_x)) << 32) | (std::uint64_t(points.front().y) - std::uint64_t(min_y)); for (std::size_t i = 0; i < points.size(); ++i) { const auto key = ((std::uint64_t(points[i].x) - std::uint64_t(min_x)) << 32) | (std::uint64_t(points[i].y) - std::uint64_t(min_y)); keys[i] = key; varying |= key ^ first; } std::vector temp(keys.size()); // 多くの桁が変化する大入力では、全桁の度数をまとめて数える。 std::array, 8> counts{}; unsigned active = 0; for (unsigned k = 0; k < 8; ++k) active += ((varying >> (k * 8)) & 255) != 0; const bool combined = convex_hull_combined_radix_counts(keys.size(), active); if (combined) { for (auto key : keys) { ++counts[0][(key >> 0) & 255]; ++counts[1][(key >> 8) & 255]; ++counts[2][(key >> 16) & 255]; ++counts[3][(key >> 24) & 255]; ++counts[4][(key >> 32) & 255]; ++counts[5][(key >> 40) & 255]; ++counts[6][(key >> 48) & 255]; ++counts[7][(key >> 56) & 255]; } } for (unsigned shift = 0; shift < 64; shift += 8) { if (((varying >> shift) & 255) == 0) continue; std::array count{}; if (combined) std::copy(counts[shift / 8].begin(), counts[shift / 8].end(), count.begin()); else for (auto key : keys) ++count[(key >> shift) & 255]; std::size_t sum = 0; for (auto& n : count) { const auto next = sum + n; n = sum; sum = next; } for (auto key : keys) temp[count[(key >> shift) & 255]++] = key; keys.swap(temp); } // 座標へ戻す前に、同じ点を表すキーを除く。 keys.erase(std::unique(keys.begin(), keys.end()), keys.end()); points.resize(keys.size()); radix_unique = true; for (std::size_t i = 0; i < keys.size(); ++i) { points[i].x = static_cast(std::int64_t(min_x) + std::int64_t(keys[i] >> 32)); points[i].y = static_cast(std::int64_t(min_y) + std::int64_t(std::uint32_t(keys[i]))); } } else std::sort(points.begin(), points.end()); } } } else if constexpr (!Sorted) std::sort(points.begin(), points.end()); if (!radix_unique) points.erase(std::unique(points.begin(), points.end(), [](const auto& a, const auto& b) { #ifndef SKIP_RUNTIME_CHECKS if constexpr (Sorted && !narrow_integer) { if (b < a) throw std::invalid_argument("convex_hull_sorted: points are not sorted"); } #endif return a == b; }), points.end()); if (points.size() <= 1) { return points; } std::vector> hull; auto left_turn = [&](const geo::Point& a, const geo::Point& b, const geo::Point& c) { if constexpr (std::is_integral_v) { if (narrow) { const auto ux = std::int64_t(b.x) - std::int64_t(a.x), uy = std::int64_t(b.y) - std::int64_t(a.y); const auto vx = std::int64_t(c.x) - std::int64_t(a.x), vy = std::int64_t(c.y) - std::int64_t(a.y); return ux * vy > uy * vx; } return a.orient(b, c) > 0; } else return geo::orientation(a, b, c, eps) > 0; }; hull.reserve(convex_hull_reserve_size(points.size(), hull.max_size())); for (const auto& p : points) { while (hull.size() >= 2 && !left_turn(hull[hull.size() - 2], hull.back(), p)) hull.pop_back(); hull.push_back(p); } std::size_t lower = hull.size(); for (std::size_t i = points.size() - 1; i-- > 0;) { while (hull.size() > lower && !left_turn(hull[hull.size() - 2], hull.back(), points[i])) hull.pop_back(); hull.push_back(points[i]); } hull.pop_back(); return hull; } } #endif namespace geo { template std::vector> convex_hull(std::vector> points, Epsilon eps = {}) { return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::convex_hull_impl(std::move(points), eps); } } #ifndef SIRKIT_CONVEX_HULL_SORTED_DEFINED #define SIRKIT_CONVEX_HULL_SORTED_DEFINED template std::vector> convex_hull_sorted(std::vector> points, geo::Epsilon eps = {}) { return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::convex_hull_impl(std::move(points), eps); } #endif namespace geo { template std::optional centroid(const std::vector>& poly, Epsilon eps = {}) { if (poly.size() < 3) return std::nullopt; C total = 0; long double sx = 0, sy = 0; [[maybe_unused]] C scale = 0; for (std::size_t i = 2; i < poly.size(); ++i) { C weight = poly[0].orient(poly[i - 1], poly[i]); total += weight; if constexpr (!std::is_integral_v) scale += std::abs(weight); long double ux = static_cast(C(poly[i - 1].x) - C(poly[0].x)), uy = static_cast(C(poly[i - 1].y) - C(poly[0].y)); long double vx = static_cast(C(poly[i].x) - C(poly[0].x)), vy = static_cast(C(poly[i].y) - C(poly[0].y)); sx += (ux + vx) * static_cast(weight); sy += (uy + vy) * static_cast(weight); } if (predicate_sign(total, scale, eps) == 0) return std::nullopt; long double denominator = 3 * static_cast(total); return RealPoint{static_cast(poly[0].x) + sx / denominator, static_cast(poly[0].y) + sy / denominator}; } template std::vector convex_cut(const std::vector>& poly, const Line& line, Epsilon eps = {}) { if (line.a == line.b) throw std::domain_error("degenerate line"); std::vector result; result.reserve(poly.size()); if (poly.empty()) return result; for (std::size_t i = 0; i < poly.size(); ++i) { const auto& a = poly[i]; const auto& b = poly[i + 1 == poly.size() ? 0 : i + 1]; int sa = orientation(line.a, line.b, a, eps), sb = orientation(line.a, line.b, b, eps); auto append = [&](const RealPoint& p) { if (result.empty() || result.back() != p) result.push_back(p); }; if (sa >= 0) append(to_real(a)); if (sa * sb < 0) { C da = line.a.orient(line.b, a), db = line.a.orient(line.b, b); long double u = static_cast(da) / (static_cast(da) - static_cast(db)); append({static_cast(a.x) + u * static_cast(C(b.x) - C(a.x)), static_cast(a.y) + u * static_cast(C(b.y) - C(a.y))}); } } if (result.size() > 1 && result.front() == result.back()) result.pop_back(); return result; } } #ifndef SIRKIT_TRIANGLE_AREA_DEFINED #define SIRKIT_TRIANGLE_AREA_DEFINED template constexpr C signed_triangle_area2(const geo::Point& a, const geo::Point& b, const geo::Point& c) { return a.orient(b, c); } template long double triangle_area(const geo::Point& a, const geo::Point& b, const geo::Point& c) { return std::abs(static_cast(signed_triangle_area2(a, b, c))) / 2; } #endif namespace geo { } #endif #ifndef SIRKIT_GEO_CIRCLE_TYPES_DEFINED #define SIRKIT_GEO_CIRCLE_TYPES_DEFINED namespace geo { enum class CircleIntersectionKind { None, Tangent, TwoPoints, Coincident }; struct CircleIntersection { CircleIntersectionKind kind = CircleIntersectionKind::None; std::vector points; }; struct Circle { RealPoint center; long double radius = 0; }; } #endif #ifndef SIRKIT_GEO_CIRCLE_DEFINED #define SIRKIT_GEO_CIRCLE_DEFINED namespace geo { template std::optional circumcircle(const Point& a, const Point& b, const Point& c, Epsilon eps = {}) { if (orientation(a, b, c, eps) == 0) return std::nullopt; 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 u2 = ux * ux + uy * uy, v2 = vx * vx + vy * vy, determinant = ux * vy - uy * vx; long double den = 2 * static_cast(determinant); long double dx = (static_cast(u2) * static_cast(vy) - static_cast(v2) * static_cast(uy)) / den; long double dy = (static_cast(ux) * static_cast(v2) - static_cast(vx) * static_cast(u2)) / den; return Circle{{static_cast(a.x) + dx, static_cast(a.y) + dy}, std::hypot(dx, dy)}; } inline void validate(const Circle& c) { if (!std::isfinite(c.center.x) || !std::isfinite(c.center.y) || !std::isfinite(c.radius) || c.radius < 0) throw std::domain_error("invalid circle"); } inline Location contains(const Circle& c, const RealPoint& p, Epsilon eps = {}) { #ifndef SKIP_RUNTIME_CHECKS validate(c); if (!std::isfinite(p.x) || !std::isfinite(p.y)) throw std::domain_error("nonfinite point"); #endif long double d = c.center.dist(p), tolerance = eps.tolerance(std::max(d, c.radius)); if (d - c.radius > tolerance) return Location::Outside; if (c.radius - d > tolerance) return Location::Inside; return Location::Boundary; } inline std::vector intersection(const Circle& c, const Line& l, Epsilon eps = {}) { #ifndef SKIP_RUNTIME_CHECKS validate(c); #endif RealPoint direction = l.b - l.a; if (direction.x == 0 && direction.y == 0) throw std::domain_error("degenerate line"); RealPoint unit = direction.normalized(), from = c.center - l.a; long double along = from.dot(unit), signed_distance = from.cross(unit), d = std::abs(signed_distance); long double tolerance = eps.tolerance(std::max(c.radius, d)); if (d - c.radius > tolerance) return {}; RealPoint foot = l.a + unit * along; if (std::abs(d - c.radius) <= tolerance) return {foot}; long double ratio = d / c.radius; long double delta = c.radius * std::sqrt(std::max(0.0L, (1 - ratio) * (1 + ratio))); return {foot - unit * delta, foot + unit * delta}; } inline std::vector intersection(const Circle& c, const Segment& s, Epsilon eps = {}) { #ifndef SKIP_RUNTIME_CHECKS validate(c); #endif if (s.a == s.b) return contains(c, s.a, eps) == Location::Boundary ? std::vector{s.a} : std::vector{}; auto points = intersection(c, Line{s.a, s.b}, eps); std::size_t write = 0; for (const auto& p : points) if (on_segment(p, s, eps)) points[write++] = p; points.resize(write); return points; } } namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ { template geo::CircleIntersection circle_intersection_impl(const geo::Circle& a, const geo::Circle& b, geo::Epsilon eps) { using geo::CircleIntersectionKind; using geo::RealPoint; #ifndef SKIP_RUNTIME_CHECKS geo::validate(a); geo::validate(b); #endif RealPoint delta = b.center - a.center; // 通常の大きさは直接平方根、極端な大きさはスケーリングするhypotを使う。 long double ax = std::abs(delta.x), ay = std::abs(delta.y); long double largest = std::max(ax, ay); long double d = largest == 0 || (largest >= 1e-150L && largest <= 1e150L) ? std::sqrt(delta.x * delta.x + delta.y * delta.y) : delta.norm(); long double r = a.radius, s = b.radius; long double tolerance = eps.tolerance(std::max({d, r, s})); if (d == 0) { if (std::abs(r - s) > tolerance) return {}; if (r == 0 || s == 0) { if constexpr (!StorePoints) return {CircleIntersectionKind::Tangent, {}}; return {CircleIntersectionKind::Tangent, {a.center}}; } return {CircleIntersectionKind::Coincident, {}}; } if (r == 0) { if (std::abs(d - s) <= tolerance) { if constexpr (!StorePoints) return {CircleIntersectionKind::Tangent, {}}; return {CircleIntersectionKind::Tangent, {a.center}}; } return {}; } if (s == 0) { if (std::abs(d - r) <= tolerance) { if constexpr (!StorePoints) return {CircleIntersectionKind::Tangent, {}}; return {CircleIntersectionKind::Tangent, {b.center}}; } return {}; } long double gap_out = (d - r) - s; long double difference = r - s; long double gap_in = std::abs(difference) - d; if (gap_out > tolerance || gap_in > tolerance) return {}; RealPoint unit = delta / d; // 許容幅内の非交差・厳密接触は、一方の円周上に接点を置く。 if (gap_out >= 0) { if constexpr (!StorePoints) return {CircleIntersectionKind::Tangent, {}}; return {CircleIntersectionKind::Tangent, {a.center + unit * r}}; } if (gap_in >= 0) { if constexpr (!StorePoints) return {CircleIntersectionKind::Tangent, {}}; return {CircleIntersectionKind::Tangent, {a.center + unit * (difference >= 0 ? r : -r)}}; } long double along = d / 2 + (difference / d) * (r / 2 + s / 2); along = std::clamp(along, -r, r); RealPoint foot = a.center + unit * along; // ほぼ同心でも交点の高さが大きい場合は2点を保つ。 if (std::abs(std::abs(along) - r) <= tolerance && std::abs(std::abs(d - along) - s) <= tolerance) { if constexpr (!StorePoints) return {CircleIntersectionKind::Tangent, {}}; return {CircleIntersectionKind::Tangent, {foot}}; } if constexpr (!StorePoints) return {CircleIntersectionKind::TwoPoints, {}}; long double ratio = along / r; long double height = r * std::sqrt(std::max(0.0L, (1 - ratio) * (1 + ratio))); RealPoint offset{-unit.y * height, unit.x * height}; return {CircleIntersectionKind::TwoPoints, {foot + offset, foot - offset}}; } } namespace geo { inline CircleIntersection intersection(const Circle& a, const Circle& b, Epsilon eps = {}) { return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::circle_intersection_impl(a, b, eps); } } #ifndef SIRKIT_CIRCLE_INTERSECTION_KIND_DEFINED #define SIRKIT_CIRCLE_INTERSECTION_KIND_DEFINED inline geo::CircleIntersectionKind circle_intersection_kind(const geo::Circle& a, const geo::Circle& b, geo::Epsilon eps = {}) { return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::circle_intersection_impl(a, b, eps).kind; } #endif namespace geo { } #endif } // namespace sirkit // SIRKIT_NAMESPACE_CLOSE_V1 // SIRKIT_NAMESPACE_END_V1 namespace sirkit {} using namespace sirkit; // SPDX-License-Identifier: CC0-1.0 // Verify I/O: Verify/current/common/fast_io.hpp // SPDX-License-Identifier: CC0-1.0 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef SIRKIT_VERIFY_FAST_IO_DEFINED #define SIRKIT_VERIFY_FAST_IO_DEFINED // VerifyInput(file=stdin): 非所有のFILEから読む。別の入力方式と混用しない。 // >> 整数: 64bit以下の十進整数を読む。検査省略時は値域内の正しい入力を前提とする。 // >> char/string: 空白を飛ばし、1文字/空白までの文字列を読む。 // >> 浮動小数点: 十進文字列を変換する。通常のCロケールで使う。 // bool / !: 直前までの読み取りが成功しているか/失敗したかを返す。 class VerifyInput { static constexpr std::size_t buffer_size = 1 << 17; std::FILE* file_; std::array buffer_; std::size_t position_ = 0, size_ = 0; bool good_ = true; int peek() { if (position_ == size_) { size_ = std::fread(buffer_.data(), 1, buffer_size, file_); buffer_[size_] = 0; // 補充後の末尾は常に数字でない番兵。 position_ = 0; if (size_ == 0) return EOF; } return buffer_[position_]; } int skip_space() { int c; while ((c = peek()) != EOF && c <= ' ') ++position_; if (c == EOF) good_ = false; return c; } public: explicit VerifyInput(std::FILE* file = stdin) : file_(file) {} VerifyInput(const VerifyInput&) = delete; VerifyInput& operator=(const VerifyInput&) = delete; explicit operator bool() const noexcept { return good_; } bool operator!() const noexcept { return !good_; } template requires (std::is_integral_v && sizeof(T) <= sizeof(std::uint64_t) && !std::is_same_v) VerifyInput& operator>>(T& result) { if (!good_) return *this; int c = skip_space(); if (c == EOF) return *this; bool negative = false; if (c == '-' || c == '+') { negative = c == '-'; ++position_; c = peek(); } if (c == EOF) { good_ = false; return *this; } #ifndef SKIP_RUNTIME_CHECKS if (c < '0' || c > '9') { good_ = false; return *this; } // 先頭の0を除けば、20桁以下の末尾直前の値はuint64_tに収まる。 while (c == '0') { ++position_; c = peek(); } std::uint64_t previous = 0; unsigned last_digit = 0; std::size_t digits = 0; #endif std::uint64_t value = 0; #ifdef SKIP_RUNTIME_CHECKS // バッファ末尾の番兵で内側の範囲判定を省き、数字が境界をまたぐときだけ補充する。 for (;;) { const unsigned char* first = buffer_.data() + position_; const unsigned char* cursor = first; while (static_cast(*cursor - '0') < 10) { value = value * 10 + static_cast(*cursor - '0'); ++cursor; } position_ += static_cast(cursor - first); if (position_ != size_) break; c = peek(); if (c == EOF) break; } #else while (c >= '0' && c <= '9') { previous = value; last_digit = static_cast(c - '0'); if (digits <= 20) ++digits; value = value * 10 + static_cast(c - '0'); ++position_; c = peek(); } #endif #ifndef SKIP_RUNTIME_CHECKS constexpr auto maximum = std::numeric_limits::max(); if ((c != EOF && c > ' ') || digits > 20 || (digits == 20 && (previous > maximum / 10 || (previous == maximum / 10 && last_digit > maximum % 10)))) { good_ = false; return *this; } std::uint64_t limit = static_cast(std::numeric_limits::max()); if constexpr (std::is_signed_v) limit += negative; else if (negative && value != 0) good_ = false; if (value > limit) good_ = false; if (!good_) return *this; #endif if constexpr (std::is_signed_v) { constexpr std::uint64_t minimum_magnitude = static_cast(std::numeric_limits::max()) + 1; // -(最小値)は評価せず、絶対値が最大値+1のときだけ最小値を使う。 result = negative ? (value == minimum_magnitude ? std::numeric_limits::min() : static_cast(-static_cast(value))) : static_cast(value); } else result = static_cast(value); return *this; } VerifyInput& operator>>(char& result) { if (!good_) return *this; const int c = skip_space(); if (c != EOF) { result = static_cast(c); ++position_; } return *this; } VerifyInput& operator>>(std::string& result) { if (!good_) return *this; int c = skip_space(); if (c == EOF) return *this; result.clear(); for (;;) { const std::size_t first = position_; while (position_ < size_ && buffer_[position_] > ' ') ++position_; result.append(reinterpret_cast(buffer_.data() + first), position_ - first); if (position_ != size_ || peek() == EOF) break; } return *this; } template requires std::is_floating_point_v VerifyInput& operator>>(T& result) { std::string token; *this >> token; if (!good_) return *this; #ifndef SKIP_RUNTIME_CHECKS char* end = nullptr; const long double value = std::strtold(token.c_str(), &end); if (end != token.c_str() + token.size()) good_ = false; else result = static_cast(value); #else result = static_cast(std::strtold(token.c_str(), nullptr)); #endif return *this; } }; // VerifyOutput(file=stdout): 非所有のFILEへ書く。破棄時にflushし、FILEは閉じない。 // << 整数/char/文字列/浮動小数点: 値を出力する。整数は64bit以下に対応する。 // fixed(digits): 浮動小数点を小数点以下digits桁で出力する(digits>=0)。 // flush(): バッファの内容をFILEへ渡す。bool / !で書き込み失敗を確認できる。 class VerifyOutput { static constexpr std::size_t buffer_size = 1 << 17; std::FILE* file_; std::array buffer_; std::size_t size_ = 0; int precision_ = 6; bool fixed_ = false, good_ = true; void write(std::string_view text) { while (!text.empty() && good_) { if (size_ == buffer_.size()) flush(); const auto count = std::min(text.size(), buffer_.size() - size_); std::memcpy(buffer_.data() + size_, text.data(), count); size_ += count; text.remove_prefix(count); } } public: explicit VerifyOutput(std::FILE* file = stdout) : file_(file) {} VerifyOutput(const VerifyOutput&) = delete; VerifyOutput& operator=(const VerifyOutput&) = delete; ~VerifyOutput() { flush(); } explicit operator bool() const noexcept { return good_; } bool operator!() const noexcept { return !good_; } VerifyOutput& fixed(int digits) { if (digits < 0) throw std::invalid_argument("negative output precision"); fixed_ = true; precision_ = digits; return *this; } void flush() noexcept { std::size_t written = 0; while (written < size_ && good_) { const auto count = std::fwrite(buffer_.data() + written, 1, size_ - written, file_); if (count == 0) good_ = false; written += count; } size_ = 0; } template requires (std::is_integral_v && sizeof(T) <= sizeof(std::uint64_t) && !std::is_same_v) VerifyOutput& operator<<(T value) { if constexpr (std::is_same_v) return *this << static_cast('0' + value); else { constexpr std::size_t capacity = std::numeric_limits::digits10 + 3; if (buffer_.size() - size_ < capacity) flush(); if (!good_) return *this; const auto end = std::to_chars(buffer_.data() + size_, buffer_.data() + size_ + capacity, value).ptr; size_ = static_cast(end - buffer_.data()); return *this; } } VerifyOutput& operator<<(char value) { if (size_ == buffer_.size()) flush(); if (good_) buffer_[size_++] = value; return *this; } VerifyOutput& operator<<(std::string_view value) { write(value); return *this; } VerifyOutput& operator<<(const std::string& value) { write(value); return *this; } VerifyOutput& operator<<(const char* value) { write(value); return *this; } template requires std::is_floating_point_v VerifyOutput& operator<<(T value) { char local[128]; const char* format = fixed_ ? "%.*Lf" : "%.*Lg"; const int count = std::snprintf(local, sizeof(local), format, precision_, static_cast(value)); if (count < 0) good_ = false; else if (static_cast(count) < sizeof(local)) write(std::string_view(local, static_cast(count))); else { std::vector text(static_cast(count) + 1); std::snprintf(text.data(), text.size(), format, precision_, static_cast(value)); write(std::string_view(text.data(), static_cast(count))); } return *this; } }; inline VerifyInput verify_in; inline VerifyOutput verify_out; #endif #include #include #include // 中心が内部、かつ全4辺への距離が半径より大きいことが必要十分。接触は不可。 // この問題の座標・半径では答え<512。O(log 512)時間・O(1)領域。 int main() { sirkit::geo::PointI center; std::int64_t radius{}; verify_in >> center.x >> center.y >> radius; std::vector polygon(4); auto fits = [&](std::int64_t d) { polygon={{d,0},{0,d},{-d,0},{0,-d}}; if (sirkit::geo::contains(polygon,center) != sirkit::geo::Location::Inside) return false; for (int i=0; i<4; ++i) { const sirkit::geo::Segment side{polygon[i],polygon[(i+1)%4]}; if (sirkit::geo::distance(center,side) <= radius) return false; } return true; }; std::int64_t low=0, high=512; while (high-low>1) { const auto middle=(low+high)/2; if (fits(middle)) high=middle; else low=middle; } verify_out << high << '\n'; }