本文へスキップ
製品デスクトップツール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
ディスカッション

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

Concepts

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

A segment tree is a data structure that answers questions about contiguous ranges of an array, such as "what is the sum of elements 3 through 7?" or "what is the minimum in this range?", and keeps those answers fast even while the array keeps changing. This chapter explains why you need one, what it looks like, and the vocabulary used in the rest of the guide.

The problem: queries and updates mixed together

Suppose an array of length n receives a long stream of two kinds of requests:

  • Point update: change the value of a[i].
  • Range query: return the sum (or minimum, or maximum) of a[l] through a[r-1].

The simplest approach keeps the plain array and loops over the range for every query. Updates cost O(1), but each query costs O(n).

a = [5, 3, 7, 9, 6, 4, 1, 2]

def update(i, value):
    a[i] = value          # O(1)

def query(l, r):
    return sum(a[l:r])    # O(n): adds every element in the range

Prefix sums versus a segment tree

If the values never change, prefix sums are hard to beat. Store in prefix[i] the sum of the first i elements, and any range sum becomes a single subtraction. The catch is that changing one element invalidates every prefix sum after it, so an update costs O(n).

from itertools import accumulate

a = [5, 3, 7, 9, 6, 4, 1, 2]
prefix = [0, *accumulate(a)]   # [0, 5, 8, 15, 24, 30, 34, 35, 37]

def query(l, r):
    return prefix[r] - prefix[l]   # O(1)

def update(i, value):
    diff = value - a[i]
    a[i] = value
    for k in range(i + 1, len(prefix)):   # O(n): fix every later prefix
        prefix[k] += diff

print(query(2, 6))   # 26
ApproachPoint updateRange queryGood fit
Plain arrayO(1)O(n)Queries are rare
Prefix sumsO(n)O(1)Values never change
Segment treeO(log n)O(log n)Updates and queries interleave

Instead of making one operation extremely fast and the other slow, a segment tree makes both operations `O(log n)`. With hundreds of thousands of requests, that is the difference between seconds and hours.

What the tree looks like

A segment tree is a binary tree in which every node is responsible for one range of the array and stores a of that range (its sum, minimum, and so on).

この章について質問がありますか?
次の章How It Works
summary
  • The root covers the whole range [0, n).
  • A node covering [lo, hi) splits at the midpoint mid: the left child covers [lo, mid) and the right child covers [mid, hi).
  • A leaf covers a range of length 1, that is, a single element.
  • An internal node stores the combination of its two children.

Because each split halves the range, the tree has height about log2 n. Any query range can be covered by a handful of disjoint nodes (at most two per level), and changing one element only requires recomputing the single path from that leaf to the root. That is why both operations run in O(log n).

What the combine operation must satisfy

The operation stored in the tree must be associative, and the implementation is cleanest when it also has an identity element. In algebra this structure is called a monoid.

import math

# (combine function, identity)
SUM = (lambda x, y: x + y, 0)
MIN = (min, math.inf)
MAX = (max, -math.inf)
GCD = (math.gcd, 0)
XOR = (lambda x, y: x ^ y, 0)

op, identity = MIN
print(op(op(4, 9), 2) == op(4, op(9, 2)))   # True: associativity
print(op(identity, 7))                      # 7: the identity changes nothing

A question like "what is the median of this range?" does not fit: the parent's answer cannot be computed from the two children's summaries alone, so a basic segment tree cannot answer it.

Vocabulary

  • Node and segment: a cell of the tree and the slice of the array it covers.
  • Combine (merge): the operation that turns two child values into the parent value.
  • Identity: the neutral value returned for nodes outside the query, such as 0 for sums and infinity for minimums.
  • Point update and range query: the two operations a basic segment tree supports.
  • Range update: a request such as "add 3 to every element in this range", handled with lazy propagation.
  • Fenwick tree (binary indexed tree, BIT): a shorter, lighter alternative specialized for invertible operations such as sums.

When to use it

  • Array values change often, and range sums, minimums, or maximums are queried in between.
  • You repeatedly count "how many elements seen so far are smaller than x" over sorted coordinates.
  • A sweep line opens and closes intervals and needs to maintain aggregate state as it moves.

If the values never change, prefix sums or a sparse table are simpler and faster.

Summary

A segment tree stores a summary for every range obtained by repeatedly halving the array, which makes both point updates and range queries O(log n). As long as the combine operation is associative and has an identity, the same structure answers sums, minimums, maximums, GCDs, and more. The next chapter builds a tree by hand and traces queries and updates through it.

コメント 0件

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

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