本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開TASTEWINMファイル管理開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペース投資TASTESTOCK株式自動売買デスクトップアプリはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらくTASTEWINM2つの画面で整理する、キーボード中心のファイルマネージャー

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

投資

TASTESTOCKいつ・何を。自分で決めたルールどおりに動く株式自動売買

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシー会社概要プライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
昨日
累計閲覧
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

セグメント木 ドキュメント
セグメント木
ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
ディスカッション

セグメント木 ガイド · 2/6

How It Works

この章は現在、英語でのみ提供しています。

This chapter builds a segment tree for the array a = [5, 3, 7, 9, 6, 4, 1, 2] and traces, step by step, how a range-sum query and a point update move through it. It then shows the iterative bottom-up variant and the idea behind lazy propagation for range updates.

Step 1: build the tree

The most common layout numbers nodes from 1 and gives node k the children 2k and 2k+1. Elements go into the leaves, and each parent stores the sum of its two children.

                 [0,8) 37
           /                  \
      [0,4) 24              [4,8) 13
      /      \              /      \
  [0,2) 8  [2,4) 16    [4,6) 10  [6,8) 3
   /  \     /  \        /  \      /  \
  5    3   7    9      6    4    1    2

There are 2n - 1 nodes and each one is computed once, so building takes O(n).

Step 2: query the range [2, 6)

We want a[2] + a[3] + a[4] + a[5]. Starting at the root, every node falls into one of three cases:

  • The node's range does not overlap the query: return the identity, 0.
  • The node's range lies completely inside the query: return the stored value.
  • The ranges partly overlap: recurse into both children and add the results.
Node visitedRelation to [2,6)Returned
[0,8)partial, recurse16 + 10 = 26
[0,4)partial, recurse0 + 16 = 16
[0,2)disjoint0
[2,4)fully inside16
[4,8)partial, recurse10 + 0 = 10
[4,6)fully inside10
[6,8)disjoint0

The answer is 26, and indeed 7 + 9 + 6 + 4 = 26. The query was covered by exactly two nodes, [2,4) and [4,6). On each level at most two nodes are "partial" and recurse further, so the number of visited nodes is O(log n).

Step 3: point update a[3] = 0

When a[3] changes from 9 to 0, fix the leaf [3,4) and recompute only its ancestors:

  • [3,4): 9 becomes 0
  • [2,4): 16 becomes 7 + 0 = 7
  • [0,4): 24 becomes 8 + 7 = 15
  • [0,8): 37 becomes 15 + 13 = 28

Only one leaf-to-root path changed: nodes. Translating the three steps directly into recursive functions gives:

この章について質問がありますか?
前の章Concepts次の章Implementation
log2 8 + 1 = 4
a = [5, 3, 7, 9, 6, 4, 1, 2]
n = len(a)
tree = [0] * (4 * n)

def build(node, lo, hi):
    if hi - lo == 1:
        tree[node] = a[lo]
        return
    mid = (lo + hi) // 2
    build(2 * node, lo, mid)
    build(2 * node + 1, mid, hi)
    tree[node] = tree[2 * node] + tree[2 * node + 1]

def query(node, lo, hi, l, r):
    if r <= lo or hi <= l:          # disjoint
        return 0
    if l <= lo and hi <= r:         # fully inside
        return tree[node]
    mid = (lo + hi) // 2            # partial overlap
    return query(2 * node, lo, mid, l, r) + query(2 * node + 1, mid, hi, l, r)

def update(node, lo, hi, i, value):
    if hi - lo == 1:
        tree[node] = value
        return
    mid = (lo + hi) // 2
    if i < mid:
        update(2 * node, lo, mid, i, value)
    else:
        update(2 * node + 1, mid, hi, i, value)
    tree[node] = tree[2 * node] + tree[2 * node + 1]

build(1, 0, n)
print(query(1, 0, n, 2, 6))   # 26
update(1, 0, n, 3, 0)
print(query(1, 0, n, 2, 6))   # 17

When n is not a power of two the tree becomes slightly lopsided and node numbers can exceed 2n, which is why the array is allocated with 4n slots.

The iterative bottom-up variant

The same work can be done without recursion. Put the elements in the second half of an array of size 2n, tree[n..2n), then compute tree[i] = tree[2i] + tree[2i+1] for i from n-1 down to 1. A query starts at the two ends lo = l + n and hi = r + n and climbs toward the root, adding only the nodes that sit on the boundary.

a = [5, 3, 7, 9, 6, 4, 1, 2]
n = len(a)
tree = [0] * n + a
for i in range(n - 1, 0, -1):
    tree[i] = tree[2 * i] + tree[2 * i + 1]

lo, hi, total = 2 + n, 6 + n, 0
while lo < hi:
    if lo & 1:                 # lo is a right child: take it, step right
        total += tree[lo]; lo += 1
    if hi & 1:                 # hi is a right child: take its left neighbor
        hi -= 1; total += tree[hi]
    print(f"lo={lo} hi={hi} total={total}")
    lo //= 2; hi //= 2
print(total)                   # 26
Roundlo, hi at startNodes addedtotal
110, 14none0
25, 7tree[5]=16, tree[6]=1026
33, 3loop ends26

Range updates and lazy propagation

Handling "add 2 to every element of [0,4)" as four point updates costs O(k log n). Lazy propagation instead stops at nodes that are fully covered by the update and leaves them a note (the lazy value) saying "my children still owe +2".

add +2 to [0,4)
  [0,4): 24 + 2 * 4 = 32, lazy = 2   (children untouched)
  [0,8): 32 + 13 = 45

later, a query for [2,4) passes through [0,4) and pushes the note down
  [0,2): 8 + 2 * 2 = 12, lazy = 2
  [2,4): 16 + 2 * 2 = 20, lazy = 2
  [0,4): lazy = 0

A note is only resolved when some operation needs to descend below that node, so range updates also finish in O(log n). The full code appears in the practice problems chapter.

Summary

A segment tree stores the sum of every halved range; queries descend according to overlap, and updates recompute a single leaf-to-root path. The iterative variant does the same job with a 2n array and short loops, while lazy propagation defers range updates and pushes them to children only when needed.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。