Amortized Analysis 主講人:陳建源 研究室 :法401 Email: [email protected] 日期:99/12/18 Outline Analysis of algorithms Aggregate Analysis Accounting method Potential function Analysis of algorithms Measure the goodness of algorithms Measure the difficulty of problems efficiency? asymptotic notations: O(n2) worst case average case amortized NP-complete undecidable lower bound Is the algorithm optimal? Amortized Analysis Average performance of each operation in the worst-case a sequence of n operations takes worst-case Time T(N). Amortized Analysis Aggregate Analysis-Stack operation PUSH(S,X) Multipop(S,k)k個元素,or empty worst-case Multipop => n o(n2)/n=o(n) not true 每個元素最多pop一次,n個operation 最多push n個元素,即最多有n個被pop。 ∴2n/n=2 Amortized Analysis Aggregate Analysis Incrementing a cost binary counter 0 0 0 0 0 0 1 1 0 1 0 1+2=3 0 1 1 3+1=4 1 0 0 4+3=7 logn i 0 increment worst-case k 1 n 2i n 2i 2n i 0 Total T(nk) Amortized Analysis Accounting method Differing charge to different operation [Note: 原來是一 律相同cost] actual cost +credit=amortized cost 令amortized cast actual cast ĉ c 若credit不為負 ĉ c credit 0 ĉ c c ĉ 為upper bound Amortized Analysis Accounting method Stack operation: actual cost PUSH 1 PUSH 2 POP 1 POP 0 MULTIPOP 0 MULTIPOP min(k,s) 取幾個 stack amortized cost Amortized Analysis Accounting method PUSH:即一個cost為實際cost 另一個為credit預備將來POP之用 當stack有3元素,表示credit為3,而stack之元素個 數0 N N i 1 i 1 c ĉ 2N Amortized Analysis Accounting method-Increasing a binary counter 000 001 1 2 010 actual cost amortized cost 0 1 1 0 1 2 1 0 1 1 0 0 當set為1時,有 1 cost為實際成本, 另一個預備將來轉回0之用 Amortized Analysis Accounting method-Increasing a binary counter Amortized cost of an increment =2 (頂多一次set為1) credit為binary 1’s個數 N N i 1 i 1 ∴ c ĉ 2N 0 Amortized Analysis Potential function 建一 data structure D D0 D i 1 Di Di i operation Dn 建一potential function :from data structure to real number Di Amortized Analysis Potential function 針對第i個operation ĉ i ci (D i ) (D i 1 ) N N i 1 i 1 ĉ i ci (D N ) (D 0 ) if (D N ) (D 0 ) 0 N N i 1 i 1 c i ĉ i 推出 ( Di ) ( D 0 ) Amortized Analysis Potential function 如何選potential function 初值最小 將實際的cost消去 Amortized Analysis Potential function-Stack operate : the number of objects in the stack 且 (D i ) 0 (D 0 ) 0 empty stack PUSH ĉi ci (D i ) (D i 1 ) 11 2 POP ĉi ci (D i ) (D i 1 ) 1 (1) 0 MultiPOP ĉi k (k ) 0 Amortized Analysis Potential function-Incrementing a binary counter :the number of 1’s in the counter bi 第 i 個 operator 之1’s個數 ti reset ti bits 1 0 第 i 個 operation actual cost ti+1 (Di ) (Di 1 ) (bi 1 t i 1) bi 1 1 ti 當bi>0,表示bi-1-reset+1 Amortized Analysis Potential function-Incrementing a binary counter ĉ i c i (D i ) (D i 1 ) t i 1 (1 t i ) 2 (D 0 ) , (D i ) 0 N N i 1 i 1 c i ĉ i 2 N
© Copyright 2026 Paperzz