【初賽】主定理(時間複雜度)
有錯誤歡迎指出
主定理:
對於\(T(n)=aT(\dfrac{n}{b})+f(n),T(1)=O(1)\),有:
- \(f(n)=O(n^{\log_ba-\epsilon})\),\(\epsilon>0\)時,\(T(n)=\Theta(n^{\log_b a})\)
- \(f(n)=\Theta(n^{\log_ba}\log_b^l n)\)時,\(T(n)=\Theta(n^{\log_b a}\log_b^{l+1} n)\)
- \(f(n)=\Omega(n^{\log_ba+\epsilon})\),\(\epsilon>0\)且有一實數\(c\)滿足\(0<c<1,af(\dfrac{n}{b})\leq cf(n)\)
遞推式轉化和式
對於\(T(n)=aT(\dfrac{n}{b})+f(n),T(1)=O(1)\)的式子,我們假設\(n=b^k,k\)為正整數,則有:
\(T(n)=aT(\dfrac{n}{b})+f(n)\)
\(=a(aT(\dfrac{n}{b^2})+f(\dfrac{n}{b}))+f(n)\)
\(=a^2T(\dfrac{n}{b^2})+af(\dfrac{n}{b})+f(n)\)
\(=a^3T(\dfrac{n}{b^3})+a^2f(\dfrac{n}{b^2})+af(\dfrac{n}{b})+f(n)\)
\(=a^k\times T(1)+\sum\limits_{j=0}^{k-1}a^jf(\dfrac{n}{b^j})\)
\(=a^{\log_b n}+\sum\limits_{j=0}^{k-1}a^jf(\dfrac{n}{b^j})\)
\(=n^{\log_b a}+\sum\limits_{j=0}^{k-1}a^jf(\dfrac{n}{b^j})\)
上一步是由\(a^{\log_bc}=(b^{\log_ba})^{\log_bc}=b^{\log_ba\times\log_bc}=(b^{\log_bc})^{\log_ba}=c^{\log_ba}\)得到的。
接下來研究\(T(n)-n^{\log_b a}\)即可,不妨設其為\(t(n)\)。
情況1 \(f(n)=O(n^{\log_ba-\epsilon})\) ,\(\epsilon>0\)
\(t(n)=\sum\limits_{j=0}^{k-1}a^jf(\dfrac{n}{b^j})\)
\(=\sum\limits_{j=0}^{k-1}a^j(\dfrac{n}{b^j})^{\log_b a-\epsilon}\)
\(=n^{\log_b a-\epsilon}\sum\limits_{j=0}^{k-1}\dfrac{a^j}{b^{j(\log_b a-\epsilon)}}\)
\(=n^{\log_b a-\epsilon}\sum\limits_{j=0}^{k-1}\dfrac{a^jb^{j\epsilon}}{b^{j\log_b a}}\)
\(=n^{\log_b a-\epsilon}\sum\limits_{j=0}^{k-1}b^{j\epsilon}\)
\(=n^{\log_b a-\epsilon}(\dfrac{(b^\epsilon)^{k}-1}{(b^\epsilon)-1})\)
\(=n^{\log_b a-\epsilon}(\dfrac{n^{\epsilon}-1}{(b^\epsilon)-1})\)
\(=\dfrac{n^{\log_b a}-n^{\log_b a-\epsilon}}{(b^\epsilon)-1}\)
所以\(t(n)=\Theta(n^{\log_b a})\),所以\(T(n)=\Theta(n^{\log_b a})\)
情況2 \(f(n)=\Theta(n^{\log_ba}\log_b^l n)\)
\(t(n)=\sum\limits_{j=0}^{k-1}a^jf(\dfrac{n}{b^j})\)
\(=\sum\limits_{j=0}^{k-1}a^j(\dfrac{n}{b^j})^{\log_b a}\log_b^l\dfrac{n}{b^j}\)
\(=n^{\log_b a}\sum\limits_{j=0}^{k-1}\dfrac{a^j}{b^{j\log_b a}}\log_b^l\dfrac{n}{b^j}\)
\(=n^{\log_b a}\sum\limits_{j=0}^{k-1}(k-j)^l\)
\(\leq n^{\log_b a}k^{l+1}\)
\(=n^{\log_b a}\log_b^{l+1} n\)
所以\(T(n)=\Theta(n^{\log_b a}\log_b^{l+1} n)\)
情況3 \(f(n)=\Omega(n^{\log_ba+\epsilon})\),\(\epsilon>0\)且有一實數\(c\)滿足\(0<c<1,af(\dfrac{n}{b})\leq cf(n)\)
\(t(n)=\sum\limits_{j=0}^{k-1}a^jf(\dfrac{n}{b^j})\)
\(\leq \sum\limits_{j=0}^{k-1}c^jf(n)=f(n)\sum\limits_{j=0}^{k-1}c^j\)
\(\leq f(n)\sum\limits_{j=0}^{\infty}c^j\)
\(=\dfrac{f(n)}{1-c}\leq f(n)\)
所以\(t(n)=\Theta(f(n))\),且\(t(n)>O(n^{\log_b a})\),所以\(T(n)=\Theta(f(n))\)