本文へスキップ
製品デスクトップツール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製品情報は検証済みの開発ソースに基づいています。リリース・改善中

分割統治法 ドキュメント
分割統治法
Divide and Conquer: Core ConceptsHow It Works: Step-by-Step TracesImplementation: Inversions and Fast PowerComplexity: Recurrences and the Master TheoremPractice ProblemsDivide and Conquer in the Real World
ディスカッション

分割統治法 ガイド · 5/6

Practice Problems

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

Four original problems, each with an approach and a Python solution. Try each one before reading the solution: first decide how to split the input and what information has to cross the split.

Problem 1: Disagreeing judges

Two judges each rank the same n contestants from best to worst. Count the pairs of contestants that the two judges put in opposite order. n can be 200,000, so checking all pairs is too slow.

Approach: number the contestants by judge A's order, then rewrite judge B's list in those numbers. A pair is ordered differently exactly when it is an inversion in the rewritten list, so the answer is an inversion count in O(n log n).

def disagreements(judge_a, judge_b):
    rank = {name: i for i, name in enumerate(judge_a)}
    seq = [rank[name] for name in judge_b]

    def sort_count(xs):
        if len(xs) <= 1:
            return xs, 0
        mid = len(xs) // 2
        left, x = sort_count(xs[:mid])
        right, y = sort_count(xs[mid:])
        merged, i, j, cross = [], 0, 0, 0
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                merged.append(left[i])
                i += 1
            else:
                merged.append(right[j])
                j += 1
                cross += len(left) - i
        merged.extend(left[i:])
        merged.extend(right[j:])
        return merged, x + y + cross

    return sort_count(seq)[1]

print(disagreements(["ann", "bo", "cy", "di"], ["bo", "ann", "di", "cy"]))  # 2

Problem 2: Climbing a huge staircase

You climb a staircase of n steps, taking 1 or 2 steps at a time. How many different ways are there to reach the top, modulo 1_000_000_007? n can be as large as 10^18.

Approach: ways(n) = ways(n - 1) + ways(n - 2) with ways(0) = ways(1) = 1, so ways(n) is the Fibonacci number F(n + 1). A loop of 10^18 steps is impossible, but the step is a matrix: [[1, 1], [1, 0]]^n = [[F(n+1), F(n)], [F(n), F(n-1)]]. Raise the matrix to the n-th power with fast exponentiation in O(log n) matrix products.

MOD = 1_000_000_007

def mat_mult(x, y):
    return [[(x[i][0] * y[0][j] + x[i][1] * y[1][j]) % MOD for j in range(2)]
            for i in range(2)]

def mat_pow(m, e):
    if e == 0:
        return [[1, 0], [0, 1]]
    half = mat_pow(m, e // 2)
    result = mat_mult(half, half)
    return mat_mult(result, m) if e % 2 else result

def stairs(n):
    return mat_pow([[1, 1], [1, 0]], n)[0][0]

print([stairs(n) for n in range(6)])  # [1, 1, 2, 3, 5, 8]
print(stairs(10**18))

Problem 3: The k-th slowest request

A log holds the response times of requests (many values repeat). Report the k-th largest response time (k = 1 is the slowest) without sorting the whole log.

この章について質問がありますか?
前の章Complexity: Recurrences and the Master Theorem次の章Divide and Conquer in the Real World
n

Approach: quickselect on the position n - k in ascending order. Because values repeat, use a three-way split into less, equal and greater; otherwise a log full of equal values would make every step remove just one element.

import random

def kth_largest(values, k):
    target = len(values) - k            # 0-based position in ascending order
    items = list(values)
    while True:
        pivot = random.choice(items)
        less = [v for v in items if v < pivot]
        equal = [v for v in items if v == pivot]
        greater = [v for v in items if v > pivot]
        if target < len(less):
            items = less
        elif target < len(less) + len(equal):
            return pivot
        else:
            target -= len(less) + len(equal)
            items = greater

times = [120, 85, 300, 85, 95, 300, 40]
print(kth_largest(times, 1), kth_largest(times, 3))  # 300 120

The expected total work is O(n), because on average each round keeps a constant fraction of the items.

Problem 4: The best stretch of trading days

Given daily profits (some negative), find the largest total of a non-empty run of consecutive days.

Approach: the best run lies entirely in the left half, entirely in the right half, or crosses the middle. The crossing case is the best suffix of the left half plus the best prefix of the right half, found by scanning outward from the middle in O(n). That gives T(n) = 2T(n/2) + O(n) = O(n log n). (Kadane's algorithm solves this in O(n), but the divide-and-conquer version is the pattern behind segment trees.)

def max_run(a):
    def solve(lo, hi):                  # inclusive range, non-empty
        if lo == hi:
            return a[lo]
        mid = (lo + hi) // 2
        best_side = max(solve(lo, mid), solve(mid + 1, hi))
        total, best_left = 0, float("-inf")
        for i in range(mid, lo - 1, -1):
            total += a[i]
            best_left = max(best_left, total)
        total, best_right = 0, float("-inf")
        for i in range(mid + 1, hi + 1):
            total += a[i]
            best_right = max(best_right, total)
        return max(best_side, best_left + best_right)
    return solve(0, len(a) - 1)

print(max_run([3, -4, 5, -1, 2, -6, 4]))  # 6  (5 - 1 + 2)
print(max_run([-3, -1, -2]))              # -1

Summary

  • Problem 1 reduces a comparison of two rankings to an inversion count.
  • Problem 2 applies fast exponentiation to matrices instead of numbers.
  • Problem 3 needs a three-way partition so repeated values cannot slow quickselect down.
  • Problem 4 shows the crossing-middle case that many divide-and-conquer solutions share.

コメント 0件

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

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