sirkit-cpp-library

競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。

View the Project on GitHub reinsirk/sirkit-cpp-library

動的Li Chao Tree

DataStructure/dynamic-li-chao-tree.cpp · ソース · 文書 Last Commit

通常版・コンパイラ共通 · この版の一覧へ

通常版・GCC専用 · この版の一覧へ

通常版・Clang専用 · この版の一覧へ

通常版・MSVC専用 · この版の一覧へ

速度優先版・コンパイラ共通 · この版の一覧へ

速度優先版・GCC専用 · この版の一覧へ

速度優先版・Clang専用 · この版の一覧へ

速度優先版・MSVC専用 · この版の一覧へ

整数座標の閉区間で、追加した直線・線分の最小値を取得します。座標圧縮や照会座標の事前登録は不要です。

APIと前提

DynamicLiChaoTree<T, kInf>(xmin, xmax, inf=kInf)で定義域[xmin,xmax]と正の番兵infを指定します。Tは符号付き64bit以下の整数で、既定はint64_t。kInfの既定は2^60で、Tで表せない場合はTの最大値です。テンプレート引数による指定も維持します。

DynamicLiChaoTree

DynamicLiChaoTree(T xmin, T xmax, T inf = kInf);

閉区間[xmin,xmax]で使う空の木を構築します。

制約: xmin<=xmax、inf>0。

計算量: O(1)。

add_line

void add_line(T a, T b);

定義域全体へ直線y=a*x+bを追加します。

制約: 対象区間で数学的なa*x+bがTに収まり、設定したinf未満。

計算量: O(log W)。

update

void update(T a, T b);

定義域全体へ直線y=a*x+bを追加します。

制約: 対象区間で数学的なa*x+bがTに収まり、設定したinf未満。

計算量: O(log W)。

add_segment

void add_segment(T a, T b, T left, T right);

閉区間[left,right]へ線分を追加します。left>rightは無操作です。

制約: 空区間でないとき両端は定義域内で、対象区間の値がT内かつinf未満。

計算量: O(log² W)。

update_line_segment

void update_line_segment(T a, T b, T left, T right);

閉区間[left,right]へ線分を追加します。left>rightは無操作です。

制約: 空区間でないとき両端は定義域内で、対象区間の値がT内かつinf未満。

計算量: O(log² W)。

query

T query(T x) const;

最小値を返し、被覆する線がなければ設定したinfです。

制約: xは定義域内。

計算量: O(log W)。

query_line

std::optional<Line> query_line(T x) const;

最小値を与えるLineを返します。同じ最小値を与える線が複数あれば任意の1本を返し、対象区間がxを含む直線や線分がなければnulloptを返します。

制約: xは定義域内。

計算量: O(log W)。

infinity

T infinity() const noexcept;

設定したinfを返します。

制約: 追加の制約はありません。

計算量: O(1)。

empty

bool empty() const noexcept;

追加した直線・空でない線分がなければtrueです。

制約: 追加の制約はありません。

計算量: O(1)。

domain_min

T domain_min() const noexcept;

定義域の左端を返します。

制約: 追加の制約はありません。

計算量: O(1)。

domain_max

T domain_max() const noexcept;

定義域の右端を返します。

制約: 追加の制約はありません。

計算量: O(1)。

stored_nodes

std::size_t stored_nodes() const noexcept;

格納しているノードの数を返します。照会でノード数は増えません。

制約: 追加の制約はありません。

計算量: O(1)。

clear

void clear() noexcept;

全ての線を消し、容量を再利用します。

制約: 追加の制約はありません。

計算量: 格納ノード数MにO(M)。

reserve

void reserve(std::size_t n);

nノード分の容量を予約します。直線本数ではありません。

制約: ノード容量の上限以下。

計算量: 再確保時O(M)、予約済みならO(1)。

Line::Line

Line();
Line(T a, T b);

既定ではy=kInf、指定時はy=a*x+bの係数を持ちます。kInfは木ごとのinfとは別です。

制約: 係数はTの範囲内。

計算量: O(1)。

Line::get

T get(T x) const noexcept;

直線の値a*x+bを返します。

制約: 数学的な最終値がTで表現可能。

計算量: O(1)。

Line::over

bool over(const Line& other, T x) const noexcept;

xでotherより小さい値を与えればtrueです。

制約: 両直線の数学的な最終値がTで表現可能。

計算量: O(1)。

各直線・線分の対象区間内で、数学的なa*x+bがTに収まり、指定したinf未満である必要があります。中間の積だけが範囲を超え、切片との相殺で最終値が収まる場合も扱えます。線分の対象区間外の値は前提に含めません。

既定では座標と両端の値を検査します。線形関数なので、両端の確認で対象区間内の値域を判定できます。SKIP_RUNTIME_CHECKSで入力検査を除いても、内部のノード数上限は維持します。

方式と計算量

座標数をW、格納ノード数をMとすると、直線追加・照会はO(log W)、線分追加はO(log² W)、使用メモリはO(M)です。全域の64ビット整数座標でも高さは最大64です。

空の構築・状態取得はO(1)、clearはO(M)、reserveは再確保時O(M)です。コピーはO(M)で独立した木を作り、moveはO(1)です。コピー・move・clear後もinfの設定を保持します。コピー代入ではノードのコピーを先に完了させ、確保失敗時に元の定義域とノードを維持します。

完全な使用例

ソースのAPI注記
[DynamicLiChaoTree<T,kInf>]
Tの既定はint64_t、kInfの既定は2^60(Tで表せなければTの最大値)。
整数座標の閉区間で直線・線分の最小値を管理する。Tは符号付き64ビット以下の整数。
追加する線の対象区間では、数学的なa*x+bがTの範囲内かつ設定したinf未満であること。
Wを座標数とすると直線追加・取得はO(log W)、線分追加はO(log² W)。
queryは読み取り専用。SKIP_RUNTIME_CHECKSで座標・端点値の検査を除く。
DynamicLiChaoTree(xmin,xmax,inf=kInf): 閉区間[xmin,xmax]の空の木をO(1)で作る。inf>0。
infinity(): 設定したinfをO(1)で返す。コピー・移動・clearでも設定を保持する。
コピーはO(M)で独立した木を作り、moveはO(1)。M=格納ノード数。コピー代入の確保失敗時は元を維持する。
update(a, b) / add_line(a, b): 定義域全体にy=a*x+bを追加する。
update_line_segment(a, b, left, right) / add_segment(...): 閉区間[left, right]に線分を追加。left>rightは無操作。
query(x): xでの最小値を返す。被覆する線がなければ設定したinf。
query_line(x): 最小値を与えるLineを返す。同値時は任意、非被覆ならnullopt。
empty(): 追加した直線・空でない線分がなければtrue。O(1)。
clear(): 全ての線を消し、確保した容量を再利用する。O(格納ノード数)。
reserve(n): nノード分を事前確保する。直線本数とは異なる。再確保時O(M)、予約済みならO(1)。
stored_nodes(): 現在の格納ノード数を返す。取得操作では増えない。O(1)。
domain_min() / domain_max(): 定義域の左端・右端を返す。O(1)。

[DynamicLiChaoTree<T,kInf>::Line]
Line(a=0,b=kInf): y=a*x+b。既定値はテンプレート引数側で、木ごとのinf指定とは別。
get(x): a*x+bを返す。値がTで表現可能であること。
over(other, x): xでotherより小さい値を与えるときtrue。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Dynamic structures / Hash / Heap / Treap local checks dynamic_hash_local.cpp ローカル補足 —
Line Add Get Min dynamic_lichao_line.cpp 現行未照合・要再提出 AC
Segment Add Get Min dynamic_lichao_segment.cpp 現行未照合・要再提出 AC

✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。

ローカル・CI検査

検査 状態
正常系 未実施
失敗系 未測定
Library Checker公式ケース 未測定
性能測定 未実施
ASan/UBSan 未実施
カバレッジ 未実施

到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。

実行条件・件数・測定結果 · 結果JSON

Verified with

Code

// SPDX-License-Identifier: CC0-1.0
// 参考: https://nyaannyaan.github.io/library/segment-tree/dynamic-li-chao-tree.hpp
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/dynamic_li_chao.md
//
// API一覧
// [DynamicLiChaoTree<T,kInf>]
// Tの既定はint64_t、kInfの既定は2^60(Tで表せなければTの最大値)。
// 整数座標の閉区間で直線・線分の最小値を管理する。Tは符号付き64ビット以下の整数。
// 追加する線の対象区間では、数学的なa*x+bがTの範囲内かつ設定したinf未満であること。
// Wを座標数とすると直線追加・取得はO(log W)、線分追加はO(log² W)。
// queryは読み取り専用。SKIP_RUNTIME_CHECKSで座標・端点値の検査を除く。
// DynamicLiChaoTree(xmin,xmax,inf=kInf): 閉区間[xmin,xmax]の空の木をO(1)で作る。inf>0。
// infinity(): 設定したinfをO(1)で返す。コピー・移動・clearでも設定を保持する。
// コピーはO(M)で独立した木を作り、moveはO(1)。M=格納ノード数。コピー代入の確保失敗時は元を維持する。
// update(a, b) / add_line(a, b): 定義域全体にy=a*x+bを追加する。
// update_line_segment(a, b, left, right) / add_segment(...): 閉区間[left, right]に線分を追加。left>rightは無操作。
// query(x): xでの最小値を返す。被覆する線がなければ設定したinf。
// query_line(x): 最小値を与えるLineを返す。同値時は任意、非被覆ならnullopt。
// empty(): 追加した直線・空でない線分がなければtrue。O(1)。
// clear(): 全ての線を消し、確保した容量を再利用する。O(格納ノード数)。
// reserve(n): nノード分を事前確保する。直線本数とは異なる。再確保時O(M)、予約済みならO(1)。
// stored_nodes(): 現在の格納ノード数を返す。取得操作では増えない。O(1)。
// domain_min() / domain_max(): 定義域の左端・右端を返す。O(1)。
//
// [DynamicLiChaoTree<T,kInf>::Line]
// Line(a=0,b=kInf): y=a*x+b。既定値はテンプレート引数側で、木ごとのinf指定とは別。
// get(x): a*x+bを返す。値がTで表現可能であること。
// over(other, x): xでotherより小さい値を与えるときtrue。


// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <new>
#include <limits>
#include <optional>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include <vector>


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_DYNAMIC_LI_CHAO_TREE_DEFINED
#define SIRKIT_DYNAMIC_LI_CHAO_TREE_DEFINED
namespace detail {
inline void CheckLiChaoNodeCapacity(std::size_t size, std::size_t limit) {
  if (size >= limit) throw std::length_error("Li Chao node limit");
}
}

template <typename T = std::int64_t,
          T kInf = (std::numeric_limits<T>::max() < (std::int64_t{1} << 60)
                        ? std::numeric_limits<T>::max()
                        : static_cast<T>(std::int64_t{1} << 60))>
class DynamicLiChaoTree {
 public:
  struct Line {
    T slope = 0;
    T intercept = kInf;
    Line() = default;
    Line(T a, T b) : slope(a), intercept(b) {}
    T get(T x) const noexcept {
      using U = std::make_unsigned_t<T>;
      // 中間積がTを超えても、最終値が表現可能なら正確に復元できる。
      const U value = static_cast<U>(std::uint64_t(static_cast<U>(slope)) *
                                         std::uint64_t(static_cast<U>(x)) +
                                     std::uint64_t(static_cast<U>(intercept)));
      return std::bit_cast<T>(value);
    }
    bool over(const Line& other, T x) const noexcept { return get(x) < other.get(x); }
  };

 private:
  static_assert(std::is_integral_v<T> && std::is_signed_v<T> &&
                sizeof(T) <= sizeof(std::uint64_t) &&
                std::is_same_v<T, std::remove_cv_t<T>>);
  static_assert(kInf > 0);
  using Index = std::uint32_t;
  static constexpr Index no_child = std::numeric_limits<Index>::max();
  struct Node {
    Line line;
    Index left = no_child;
    Index right = no_child;
  };
  T xmin_, xmax_, inf_;
#if defined(__GNUC__) && !defined(__clang__)
  class NodeStorage {
    static_assert(std::is_trivially_copyable_v<Node> &&
                  std::is_trivially_destructible_v<Node>);
    static_assert(alignof(Node) <= alignof(std::max_align_t));
    struct Release {
      void operator()(Node* pointer) const noexcept { std::free(pointer); }
    };
    std::unique_ptr<Node, Release> owner_;
    std::size_t size_ = 0, capacity_ = 0;

   public:
    NodeStorage() noexcept = default;
    NodeStorage(const NodeStorage& other) { *this = other; }
    NodeStorage& operator=(const NodeStorage& other) {
      if (this != &other) {
        if (other.size_ > capacity_) {
          void* next = std::realloc(nullptr, other.size_ * sizeof(Node));
          if (!next) throw std::bad_alloc();
          std::memcpy(next, other.owner_.get(), other.size_ * sizeof(Node));
          owner_.reset(static_cast<Node*>(next));
          capacity_ = other.size_;
        } else if (other.size_) {
          std::memcpy(owner_.get(), other.owner_.get(), other.size_ * sizeof(Node));
        }
        size_ = other.size_;
      }
      return *this;
    }
    NodeStorage(NodeStorage&& other) noexcept
        : owner_(std::move(other.owner_)), size_(std::exchange(other.size_, 0)),
          capacity_(std::exchange(other.capacity_, 0)) {}
    NodeStorage& operator=(NodeStorage&& other) noexcept {
      if (this != &other) {
        owner_ = std::move(other.owner_);
        size_ = std::exchange(other.size_, 0);
        capacity_ = std::exchange(other.capacity_, 0);
      }
      return *this;
    }
    std::size_t size() const noexcept { return size_; }
    bool empty() const noexcept { return size_ == 0; }
    std::size_t max_size() const noexcept { return std::vector<Node>{}.max_size(); }
    Node& operator[](std::size_t index) noexcept { return owner_.get()[index]; }
    const Node& operator[](std::size_t index) const noexcept { return owner_.get()[index]; }
    void clear() noexcept { size_ = 0; }
    void reserve(std::size_t count) {
      if (count <= capacity_) return;
      if (count > max_size()) throw std::length_error("Li Chao node limit");
      if (size_ != capacity_) {
        // 未使用容量をコピーせず、有効なノードだけを移す。
        void* next = std::realloc(nullptr, count * sizeof(Node));
        if (!next) throw std::bad_alloc();
        if (size_) std::memcpy(next, owner_.get(), size_ * sizeof(Node));
        owner_.reset(static_cast<Node*>(next));
      } else {
        // 満杯なら、その場で拡張できる場合に全体コピーを避ける。
        Node* previous = owner_.release();
        void* next = std::realloc(previous, count * sizeof(Node));
        if (!next) {
          owner_.reset(previous);
          throw std::bad_alloc();
        }
        owner_.reset(static_cast<Node*>(next));
      }
      capacity_ = count;
    }
    void push_back(Node value) {
      if (size_ == capacity_) {
        const std::size_t limit = max_size();
        if (size_ == limit) throw std::length_error("Li Chao node limit");
        const std::size_t next = capacity_ == 0 ? 1 :
            capacity_ > limit - capacity_ ? limit : capacity_ * 2;
        reserve(next);
      }
      std::construct_at(owner_.get() + size_, value);
      ++size_;
    }
    void emplace_back() { push_back(Node{}); }
  };
  NodeStorage nodes_;
#else
  std::vector<Node> nodes_;
#endif

#ifndef SKIP_RUNTIME_CHECKS
  void check_coordinate(T x) const {
    if (x < xmin_ || xmax_ < x) throw std::out_of_range("Li Chao coordinate");
  }
  void check_value(const Line& line, T x) const {
    using U = std::make_unsigned_t<T>;
    const U a = line.slope < 0 ? U{} - U(line.slope) : U(line.slope);
    const U v = x < 0 ? U{} - U(x) : U(x);
    // 積そのものを作らず、64ビット全域の値と相殺を含むa*x+bを検査する。
    const auto product_at_most = [a, v](U limit) {
      return a == 0 || v <= limit / a;
    };
    bool valid;
    if ((line.slope < 0) != (x < 0)) {
      valid = product_at_most(U(line.intercept) - U(std::numeric_limits<T>::min())) &&
              (line.intercept < inf_ || !product_at_most(U(line.intercept) - U(inf_)));
    } else {
      valid = line.intercept < inf_ &&
              product_at_most(U(inf_ - 1) - U(line.intercept));
    }
    if (!valid) throw std::overflow_error("Li Chao value must fit T and be below INF");
  }
  void check_line(const Line& line, T left, T right) const {
    check_value(line, left);
    if (left != right) check_value(line, right);
  }
#endif

  static T middle_of(T left, T right) noexcept {
    using U = std::make_unsigned_t<T>;
    // left <= rightのため、符号なし差分で全整数幅の中点を求められる。
    const U distance = static_cast<U>(static_cast<U>(right) - static_cast<U>(left));
    return std::bit_cast<T>(static_cast<U>(static_cast<U>(left) + distance / 2));
  }
  Index make_node() {
    detail::CheckLiChaoNodeCapacity(nodes_.size(), std::min(static_cast<std::size_t>(no_child), nodes_.max_size()));
    const Index result = static_cast<Index>(nodes_.size());
    nodes_.push_back(Node{Line(T{}, inf_), no_child, no_child});
    return result;
  }
  Index child(Index index, bool right) {
    Index next = right ? nodes_[index].right : nodes_[index].left;
    if (next == no_child) {
      next = make_node();
      if (right) nodes_[index].right = next;
      else nodes_[index].left = next;
    }
    return next;
  }
  void insert_line(Index index, T left, T right, Line line) {
    for (;;) {
      Node& node = nodes_[index];
      if (node.line.intercept == inf_ && node.line.slope == 0) {
        node.line = line;
        return;
      }
      const bool better_left = line.over(node.line, left);
      const bool better_right = line.over(node.line, right);
      if (better_left == better_right) {
        if (better_left) node.line = line;
        return;
      }
      const T middle = middle_of(left, right);
      const bool better_middle = line.over(node.line, middle);
      if (better_middle) std::swap(node.line, line);
      if (better_left != better_middle) {
        index = child(index, false);
        right = middle;
      } else {
        index = child(index, true);
        left = static_cast<T>(middle + 1);
      }
    }
  }
  void insert_segment(Index index, T left, T right, T qleft, T qright,
                      const Line& line) {
    for (;;) {
      if (qleft <= left && right <= qright) {
        insert_line(index, left, right, line);
        return;
      }
      const Line& current = nodes_[index].line;
      // 切片kInfは空ノードを含むので枝刈りを省き、通常の探索を続ける。
      if (current.intercept != inf_) {
        // 差が最小になる重なり区間の端でも勝てなければ追加不要。
        const T endpoint = line.slope < current.slope
            ? (qright < right ? qright : right)
            : (qleft > left ? qleft : left);
        if (!line.over(current, endpoint)) return;
      }
      const T middle = middle_of(left, right);
      if (qright <= middle) {
        index = child(index, false);
        right = middle;
      } else if (middle < qleft) {
        index = child(index, true);
        left = static_cast<T>(middle + 1);
      } else {
        insert_segment(child(index, false), left, middle, qleft, qright, line);
        index = child(index, true);
        left = static_cast<T>(middle + 1);
      }
    }
  }
  template <bool ReturnLine>
  auto find_best(T x) const noexcept {
    Line best(T{}, inf_);
    T value = inf_;
    T left = xmin_, right = xmax_;
    Index index = nodes_.empty() ? no_child : Index{0};
    while (index != no_child) {
      const Node& node = nodes_[index];
      const T candidate = node.line.get(x);
      if (candidate < value) {
        value = candidate;
        if constexpr (ReturnLine) best = node.line;
      }
      if (left == right) break;
      const T middle = middle_of(left, right);
      if (x <= middle) {
        index = node.left;
        right = middle;
      } else {
        index = node.right;
        left = static_cast<T>(middle + 1);
      }
    }
    if constexpr (ReturnLine) return best;
    else return value;
  }

 public:
  DynamicLiChaoTree(T xmin, T xmax, T inf = kInf) : xmin_(xmin), xmax_(xmax), inf_(inf) {
#ifndef SKIP_RUNTIME_CHECKS
    if (xmax < xmin) throw std::invalid_argument("Li Chao domain");
    if (inf <= 0) throw std::invalid_argument("Li Chao inf must be positive");
#endif
  }
  DynamicLiChaoTree(const DynamicLiChaoTree&) = default;
  DynamicLiChaoTree(DynamicLiChaoTree&&) noexcept = default;
  DynamicLiChaoTree& operator=(const DynamicLiChaoTree& other) {
    nodes_ = other.nodes_;
    xmin_ = other.xmin_;
    xmax_ = other.xmax_;
    inf_ = other.inf_;
    return *this;
  }
  DynamicLiChaoTree& operator=(DynamicLiChaoTree&&) noexcept = default;
  void update(T a, T b) {
    const Line line(a, b);
#ifndef SKIP_RUNTIME_CHECKS
    check_line(line, xmin_, xmax_);
#endif
    if (nodes_.empty()) make_node();
    insert_line(0, xmin_, xmax_, line);
  }
  void add_line(T a, T b) { update(a, b); }
  void update_line_segment(T a, T b, T left, T right) {
    if (right < left) return;
    const Line line(a, b);
#ifndef SKIP_RUNTIME_CHECKS
    check_coordinate(left);
    check_coordinate(right);
    check_line(line, left, right);
#endif
    if (nodes_.empty()) make_node();
    insert_segment(0, xmin_, xmax_, left, right, line);
  }
  void add_segment(T a, T b, T left, T right) {
    update_line_segment(a, b, left, right);
  }
  T query(T x) const {
#ifndef SKIP_RUNTIME_CHECKS
    check_coordinate(x);
#endif
    return find_best<false>(x);
  }
  std::optional<Line> query_line(T x) const {
#ifndef SKIP_RUNTIME_CHECKS
    check_coordinate(x);
#endif
    Line result = find_best<true>(x);
    if (result.slope == 0 && result.intercept == inf_) return std::nullopt;
    return result;
  }
  bool empty() const noexcept { return nodes_.empty(); }
  T infinity() const noexcept { return inf_; }
  void clear() noexcept { nodes_.clear(); }
  void reserve(std::size_t count) {
    if (count > no_child || count > nodes_.max_size())
      throw std::length_error("Li Chao node limit");
    nodes_.reserve(count);
  }
  std::size_t stored_nodes() const noexcept { return nodes_.size(); }
  T domain_min() const noexcept { return xmin_; }
  T domain_max() const noexcept { return xmax_; }
};
#endif

} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1
Back to top page