#define SKIP_RUNTIME_CHECKS // Verify: https://yukicoder.me/problems/no/716 // Library: Geometry/Nearest_Two_points.cpp // SPDX-License-Identifier: CC0-1.0 // ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/nearest_two_points.md // // API一覧 // [最近点対] // P: pairの別名。NearestTwoPointsResultはdistance_squared:uint64_tとfirst_index/second_index:size_tを所有。 // NearestTwoPointsResult::distance_squaredは最短距離の二乗、添字は元入力の0始まり(first_index < second_index)。 // nearest_two_points(first,last): [first,last)の整数pair-like列からoptionalを返す。int32座標・未整列可・入力不変、O(N log N)時間/O(N)領域。 // 2点未満はnullopt。同距離の対は任意。最小二乗距離がuint64_tを超える場合は常時overflow_error。 // nearest_two_points(first,count): firstからptrdiff_t型のcount個を処理する。同じ戻り値・計算量。count>=0で、指定個数を参照できること。 // nearest_two_points(points): vector全体を処理する。同じ戻り値・計算量。元入力の点番号を結果に保持する。 // closest_pair(first,n): firstからn個の最短距離二乗をuint64_tで返す。n<2はINT32_MAX(負数は検査時に例外)。 // int32座標・未整列可・入力不変、O(N log N)時間/O(N)領域。uint64_t超過は常時overflow_error。 // nearest_two_points_sorted(first,last): 整列済み範囲版。(x,y)辞書順の非減少を前提に初回sortを省く。検査時はコピー中に順序を確認。 // 戻り値はnearest_two_pointsと同じで、添字は渡した列内。O(N log N)時間/O(N)領域、入力不変。 // nearest_two_points_sorted(first,count): 整列済みfirstからcount個の版。count>=0かつ指定個数を参照可能。戻り値・計算量は範囲版と同じ。 // nearest_two_points_sorted(points): 整列済みvector全体版。戻り値・前提・計算量は範囲版と同じ。 // SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。 #include #include #include #include #include #include #include #include #include #include #include #include // SIRKIT_NAMESPACE_OPEN_V1 namespace sirkit { #ifndef SIRKIT_NEAREST_TWO_POINTS_TYPES_DEFINED #define SIRKIT_NEAREST_TWO_POINTS_TYPES_DEFINED using P = std::pair; struct NearestTwoPointsResult { std::uint64_t distance_squared; std::size_t first_index; std::size_t second_index; }; #endif #ifndef SIRKIT_INTERNAL_NEAREST_TWO_POINTS_DEFINED #define SIRKIT_INTERNAL_NEAREST_TWO_POINTS_DEFINED namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ { template class NearestTwoPointsSolver { struct Node { std::int32_t x; std::int32_t y; Index index; // 作業領域は各整列パスで全要素を代入してから読む。 Node() noexcept {} Node(std::int32_t a, std::int32_t b, Index i) noexcept : x(a), y(b), index(i) {} }; #if (defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__) && \ !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) // GCC/Clangの整数拡張。標準C++の型ではない。 __extension__ using Distance = unsigned __int128; // 差はUINT32_MAX以下なので、単独の二乗は64bitに収まる。 static Distance square(std::uint64_t d) { return Distance(d * d); } static Distance add(Distance a, Distance b) { return a + b; } static std::uint64_t narrow(Distance d) { if (d > std::numeric_limits::max()) throw std::overflow_error("nearest_two_points: squared distance exceeds uint64_t"); return static_cast(d); } #else // 座標差は32ビット以内。二乗和だけ65ビット必要になる。 struct Distance { std::uint64_t low; bool high; friend bool operator<(Distance a, Distance b) { return a.high != b.high ? !a.high : a.low < b.low; } }; static Distance square(std::uint64_t d) { return {d * d, false}; } static Distance add(Distance a, Distance b) { const auto low = a.low + b.low; return {low, low < a.low}; } static std::uint64_t narrow(Distance d) { if (d.high) throw std::overflow_error("nearest_two_points: squared distance exceeds uint64_t"); return d.low; } #endif // 外接矩形内の全距離が64bitに収まる経路で使う。 static std::uint64_t low(const Distance& value) { #if (defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__) && !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) return static_cast(value); #else return value.low; #endif } static Distance from_low(std::uint64_t value) { #if (defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__) && !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) return Distance(value); #else return {value, false}; #endif } static bool fits_low(const Distance& value) { #if (defined(__GNUC__) || defined(__clang__)) && defined(__SIZEOF_INT128__) && !defined(SIRKIT_FORCE_STANDARD_ARITHMETIC) return value <= std::numeric_limits::max(); #else return !value.high; #endif } std::vector nodes_; std::vector buffer_; Distance best_{}; std::size_t best_first_ = 0; std::size_t best_second_ = 1; bool zero_ = false; #ifndef SKIP_RUNTIME_CHECKS template static bool valid_coordinate(Integer value) { if constexpr (std::numeric_limits::digits <= 31) { return true; } else if constexpr (std::is_signed_v) { return value >= static_cast(std::numeric_limits::min()) && value <= static_cast(std::numeric_limits::max()); } else { return value <= static_cast(std::numeric_limits::max()); } } #endif static std::uint64_t difference(std::int32_t a, std::int32_t b) { const std::int64_t d = std::int64_t(a) - b; return static_cast(d < 0 ? -d : d); } static Distance distance(const Node& a, const Node& b) { return add(square(difference(a.x, b.x)), square(difference(a.y, b.y))); } static bool by_y(const Node& a, const Node& b) { return a.y != b.y ? a.y < b.y : a.x < b.x; } void update(const Node& a, const Node& b) { const auto d = distance(a, b); if (d < best_) { best_ = d; best_first_ = std::min(a.index, b.index); best_second_ = std::max(a.index, b.index); #if defined(__GNUC__) && !defined(__clang__) // GCCでは計算済みの65bit距離を使う。Clangは座標比較を維持する。 zero_ = !(square(0) < d); #else zero_ = a.x == b.x && a.y == b.y; #endif } } // 呼出側で二乗和がUINT64_MAX以下であることを保証する。 void update64(const Node& a, const Node& b) { const auto dx = difference(a.x, b.x), dy = difference(a.y, b.y); const auto d = dx * dx + dy * dy; if (d < low(best_)) { best_ = from_low(d); best_first_ = std::min(a.index, b.index); best_second_ = std::max(a.index, b.index); #if defined(__GNUC__) && !defined(__clang__) // GCCでは計算済みの65bit距離を使う。Clangは座標比較を維持する。 zero_ = d == 0; #else zero_ = a.x == b.x && a.y == b.y; #endif } } // 符号bitを反転したxを10/11/11bitの3パスで基数整列する。 template unsigned sort_by_coordinate() { [[maybe_unused]] std::int32_t min_y = std::numeric_limits::max(); [[maybe_unused]] std::int32_t max_y = std::numeric_limits::min(); // Indexの範囲内の点数を扱うので、合計と最終offsetも同じ型に収まる。 std::array, 3> counts{}; for (const auto& node : nodes_) { if constexpr (!ByY) { min_y = std::min(min_y, node.y); max_y = std::max(max_y, node.y); } const auto key = static_cast(ByY ? node.y : node.x) ^ UINT32_C(0x80000000); ++counts[0][key & 1023U]; ++counts[1][(key >> 10) & 2047U]; ++counts[2][key >> 21]; } buffer_.resize(nodes_.size()); Node* input = nodes_.data(); Node* output = buffer_.data(); for (unsigned pass = 0; pass < 3; ++pass) { auto& offsets = counts[pass]; std::size_t active = 0; for (const auto count : offsets) active += count != 0; if (active <= 1) continue; Index sum = 0; for (auto& count : offsets) { const auto n = count; count = sum; sum += n; } for (std::size_t i = 0; i < nodes_.size(); ++i) { const auto key = static_cast(ByY ? input[i].y : input[i].x) ^ UINT32_C(0x80000000); output[offsets[(key >> (pass == 0 ? 0 : pass == 1 ? 10 : 21)) & (pass == 0 ? 1023U : 2047U)]++] = input[i]; } std::swap(input, output); } if (input != nodes_.data()) nodes_.swap(buffer_); // bit0は64bit距離、bit1は全点が同じy座標。 if constexpr (!ByY) { return unsigned(fits_low(add(square(difference(nodes_.back().x, nodes_.front().x)), square(difference(max_y, min_y))))) | (unsigned(min_y == max_y) << 1); } else return 0; } // 同区間の両配列をx順で開始し、outputをy順で返す。inputは作業用。 void solve(Node* input, Node* output, std::size_t left, std::size_t right) { if (zero_) return; if (right - left <= 16) { for (auto i = left; i < right; ++i) for (auto j = i + 1; j < right; ++j) update(output[i], output[j]); std::sort(output + left, output + right, by_y); return; } const auto middle = left + (right - left) / 2; const auto split_x = input[middle].x; solve(output, input, left, middle); solve(output, input, middle, right); if (zero_) return; // 左半分のxは右半分以下。同じyでは左を先にすればよい。 std::merge(input + left, input + middle, input + middle, input + right, output + left, [](const Node& a, const Node& b) { return a.y < b.y; }); auto used = left; for (auto i = left; i < right; ++i) { const Node current = output[i]; if (!(square(difference(current.x, split_x)) < best_)) continue; for (auto j = used; j > left;) { const Node& previous = input[--j]; if (!(square(difference(current.y, previous.y)) < best_)) break; update(current, previous); if (zero_) return; } input[used++] = current; } } // 座標順なので、1軸だけで現在の最短距離以上なら以降も候補にならない。 template void scan_leaf64(const Node* points, std::size_t left, std::size_t right) { for (auto i = left; i < right; ++i) for (auto j = i + 1; j < right; ++j) { const auto delta = ByY ? difference(points[i].y, points[j].y) : difference(points[i].x, points[j].x); if (!(delta * delta < low(best_))) break; update64(points[i], points[j]); if (zero_) return; } } void solve64(Node* input, Node* output, std::size_t left, std::size_t right) { if (zero_) return; if (right - left <= 16) { const auto span_x = difference(output[left].x, output[right - 1].x); std::sort(output + left, output + right, by_y); const auto span_y = difference(output[left].y, output[right - 1].y); // inputはx順、outputはy順。広がりの大きい軸で打ち切る。 if (span_y >= span_x) scan_leaf64(output, left, right); else scan_leaf64(input, left, right); return; } const auto middle = left + (right - left) / 2; const auto split_x = input[middle].x; solve64(output, input, left, middle); solve64(output, input, middle, right); if (zero_) return; // 左半分のxは右半分以下。同じyでは左を先にすればよい。 std::merge(input + left, input + middle, input + middle, input + right, output + left, [](const Node& a, const Node& b) { return a.y < b.y; }); auto used = left; for (auto i = left; i < right; ++i) { const Node current = output[i]; const auto dx = difference(current.x, split_x); if (!(dx * dx < low(best_))) continue; for (auto j = used; j > left;) { const Node& previous = input[--j]; const auto dy = difference(current.y, previous.y); if (!(dy * dy < low(best_))) break; update64(current, previous); if (zero_) return; } input[used++] = current; } } public: template::max(), std::input_iterator Iterator, std::sentinel_for Sentinel> static std::optional run(Iterator first, Sentinel last) { NearestTwoPointsSolver solver; const auto capacity = std::min(kNodeLimit, solver.nodes_.max_size()); if constexpr (std::sized_sentinel_for) { const auto count = last - first; #ifndef SKIP_RUNTIME_CHECKS if (count < 0) throw std::invalid_argument("nearest_two_points: reversed range"); #endif if (std::cmp_greater(count, capacity)) throw std::length_error("nearest_two_points: too many points"); solver.nodes_.reserve(static_cast(count)); } for (; first != last; ++first) { const auto& point = *first; static_assert(std::integral> && std::integral>, "nearest_two_points requires integral pair coordinates"); #ifndef SKIP_RUNTIME_CHECKS if (!valid_coordinate(point.first) || !valid_coordinate(point.second)) throw std::out_of_range("nearest_two_points: coordinates must fit int32_t"); #endif if (solver.nodes_.size() == capacity) throw std::length_error("nearest_two_points: too many points"); #ifndef SKIP_RUNTIME_CHECKS if constexpr (Sorted) { if (!solver.nodes_.empty()) { const auto& previous = solver.nodes_.back(); if (static_cast(point.first) < previous.x || (static_cast(point.first) == previous.x && static_cast(point.second) < previous.y)) throw std::invalid_argument("nearest_two_points_sorted: unordered input"); } } #endif solver.nodes_.push_back({static_cast(point.first), static_cast(point.second), static_cast(solver.nodes_.size())}); } if (solver.nodes_.size() < 2) return std::nullopt; if constexpr (!Sorted) { if (solver.nodes_.size() == 2) return NearestTwoPointsResult{narrow(distance(solver.nodes_[0], solver.nodes_[1])), 0, 1}; } [[maybe_unused]] unsigned coordinate_flags = 0; if constexpr (!Sorted) { if (solver.nodes_.size() >= 2048) { if (solver.nodes_[0].x == solver.nodes_[1].x && solver.nodes_[0].y == solver.nodes_[1].y) return NearestTwoPointsResult{0, 0, 1}; coordinate_flags = solver.sort_by_coordinate(); } else std::sort(solver.nodes_.begin(), solver.nodes_.end(), [](const Node& a, const Node& b) { return a.x != b.x ? a.x < b.x : a.y < b.y; }); } if constexpr (!Sorted) { if (solver.nodes_.front().x == solver.nodes_.back().x) { if (solver.nodes_.size() >= 2048) solver.template sort_by_coordinate(); coordinate_flags |= 4U; // bit2は全点が同じx座標。 } } solver.best_ = distance(solver.nodes_[0], solver.nodes_[1]); solver.best_first_ = std::min(solver.nodes_[0].index, solver.nodes_[1].index); solver.best_second_ = std::max(solver.nodes_[0].index, solver.nodes_[1].index); solver.zero_ = solver.nodes_[0].x == solver.nodes_[1].x && solver.nodes_[0].y == solver.nodes_[1].y; if constexpr (!Sorted) { if (!solver.zero_ && (coordinate_flags & 6U)) { for (std::size_t i = 2; i < solver.nodes_.size(); ++i) { solver.update64(solver.nodes_[i - 1], solver.nodes_[i]); if (solver.zero_) break; } return NearestTwoPointsResult{narrow(solver.best_), solver.best_first_, solver.best_second_}; } } if (!solver.zero_) { // 最初だけ両配列のx順を揃える。 solver.buffer_ = solver.nodes_; if constexpr (!Sorted) { if (coordinate_flags & 1U) solver.solve64(solver.nodes_.data(), solver.buffer_.data(), 0, solver.nodes_.size()); else solver.solve(solver.nodes_.data(), solver.buffer_.data(), 0, solver.nodes_.size()); } else solver.solve(solver.nodes_.data(), solver.buffer_.data(), 0, solver.nodes_.size()); } return NearestTwoPointsResult{narrow(solver.best_), solver.best_first_, solver.best_second_}; } }; } // namespace reinsirk::detail #endif #ifndef SIRKIT_NEAREST_TWO_POINTS_DEFINED #define SIRKIT_NEAREST_TWO_POINTS_DEFINED template Sentinel> std::optional nearest_two_points(Iterator first, Sentinel last) { // 小入力はsize_t経路を保ち、大入力だけ点ごとの添字を圧縮する。 if constexpr (std::sized_sentinel_for) { const auto n = last - first; if (n >= 2048 && std::cmp_less_equal(n, std::numeric_limits::max())) return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::NearestTwoPointsSolver::run(std::move(first), std::move(last)); } return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::NearestTwoPointsSolver::run(std::move(first), std::move(last)); } template std::optional nearest_two_points(Iterator first, std::ptrdiff_t count) { #ifndef SKIP_RUNTIME_CHECKS if (count < 0) throw std::invalid_argument("nearest_two_points: negative count"); #endif return nearest_two_points(std::counted_iterator(std::move(first), count), std::default_sentinel); } template std::optional nearest_two_points(const std::vector& points) { return nearest_two_points(points.begin(), points.end()); } #endif #ifndef SIRKIT_CLOSEST_PAIR_DEFINED #define SIRKIT_CLOSEST_PAIR_DEFINED template std::uint64_t closest_pair(Iterator first, int n) { const auto result = nearest_two_points(std::move(first), static_cast(n)); return result ? result->distance_squared : std::numeric_limits::max(); } #endif #ifndef SIRKIT_NEAREST_TWO_POINTS_SORTED_DEFINED #define SIRKIT_NEAREST_TWO_POINTS_SORTED_DEFINED template Sentinel> std::optional nearest_two_points_sorted(Iterator first, Sentinel last) { // 小入力はsize_t経路を保ち、大入力だけ点ごとの添字を圧縮する。 if constexpr (std::sized_sentinel_for) { const auto n = last - first; if (n >= 2048 && std::cmp_less_equal(n, std::numeric_limits::max())) return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::NearestTwoPointsSolver::run(std::move(first), std::move(last)); } return /*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::NearestTwoPointsSolver::run(std::move(first), std::move(last)); } template std::optional nearest_two_points_sorted(Iterator first, std::ptrdiff_t count) { #ifndef SKIP_RUNTIME_CHECKS if (count < 0) throw std::invalid_argument("nearest_two_points_sorted: negative count"); #endif return nearest_two_points_sorted(std::counted_iterator(std::move(first), count), std::default_sentinel); } template std::optional nearest_two_points_sorted(const std::vector& points) { return nearest_two_points_sorted(points.begin(), points.end()); } #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 // 非減少の1次元列をy=0へ置く。最近点対のdistance_squaredを実出力へ反映。 // 整列済みAPIでもO(N log N)時間・O(N)領域。二乗距離は完全平方数。 int main() { int n{}; verify_in >> n; std::vector points(n); for (auto& point : points) verify_in >> point.first; const auto answer=sirkit::nearest_two_points_sorted(points); const auto distance=static_cast(std::sqrt(static_cast(answer->distance_squared))); verify_out << distance << '\n' << static_cast(points.back().first)-points.front().first << '\n'; }