Try   HackMD

Ch4:Divide-and-Conquer

分治法是透過將原問題分解成幾個規模較小、形式相同或相似的子問題,遞迴地解決各子問題,最後再將這些子問題的解合併,得到原問題的解。

基本步驟

所有分治法皆可拆分為三個步驟:

  1. Divide(分割):把大規模問題分割成好幾個小問題
  2. Conquer(征服):對每個小問題遞迴求解
  3. Combine(合併):整合小問題的答案,形成原問題的答案

範例:矩陣乘法

n×n 矩陣乘法可以透過分治法來加快執行時間

  • 問題:
    A×B=C
  • 先把
    n×n
    矩陣分割成 4 個
    n2×n2
    矩陣
  • A=(A11A12A21A22),B=(B11B12B21B22)
  • C=A×B=(A11A12A21A22)×(B11B12B21B22)=(A11×B11+A12×B21A11×B12+A12×B22A21×B11+A22×B21A21×B12+A22×B22)
  • 我們必須求出這八個小乘法然後加起來,就可以得到 C 的答案
  • Presudo code
    Image Not Showing Possible Reasons
    • The image was uploaded to a note which you don't have access to
    • The note which the image was originally uploaded to has been deleted
    Learn More →
  • 遞迴式:
    T(n)=8T(n/2)+Θ(1)

遞迴式轉一般式的解法

替換法(Substitution Method):

  • 先猜測遞迴式的解
  • 利用 數學歸納法 或 直接替換來證明

遞迴樹法(Recursion-Tree Methods):

  • 將遞迴關係化成一顆樹,每一層代表一次分割子問題
  • 步驟:
    • 範例:
      T(n)=3T(n/4)+Θ(n2)
    • 先畫出第一層:
      Image Not Showing Possible Reasons
      • The image was uploaded to a note which you don't have access to
      • The note which the image was originally uploaded to has been deleted
      Learn More →
    • 然後畫出第二層:
      Image Not Showing Possible Reasons
      • The image was uploaded to a note which you don't have access to
      • The note which the image was originally uploaded to has been deleted
      Learn More →
    • 第三層:
      • T(n/4)=3T(n/16)+Θ((n/4)2)

        Image Not Showing Possible Reasons
        • The image was uploaded to a note which you don't have access to
        • The note which the image was originally uploaded to has been deleted
        Learn More →
    • 依此類推,然後每一層加起來找規律:
      Image Not Showing Possible Reasons
      • The image was uploaded to a note which you don't have access to
      • The note which the image was originally uploaded to has been deleted
      Learn More →

主定理(Master Theorem)

主定理並非萬用,必須遞迴式符合格式才可以用

  • 當遞迴式為
    T(n)=aT(n/b)+f(n)
    時:
    • Case 1:當
      f(n)nlogba0
      • f(n)<nlogba
      • T(n)=Θ(nlogba)
    • Case 2:當
      f(n)nlogba=constant
      • f(n)=nlogba
      • T(n)=Θ(f(n)lgn)
    • Case 3:當
      f(n)nlogba
      • 滿足
        for ϵ>0, f(n)=Ω(nlogbaϵ)
      • 正規化條件
        • 滿足
          af(n/b)cf(n)
        • f(n)
          多項式函數
      • f(n)>nlogba
      • T(n)=Θ(f(n))