Recurrences
알고리즘이 재귀적인 함수 호출을 사용하는 경우, 그것의 running time은 recurrence 형태로 설명될 수 있다.
Recurrence는 더 작은 크기의 입력을 가진 함수로 원래의 함수를 설명하는 것이다.
Solving recurrences
Asymptotic bounds를 사용한다.
The substitution method
- Form a recursive form.
- Guess the solution
- Use mathemetical induction to prove the guess is right
Example1
Determining an upper bound on the recurrence
T(n)=2T(⌊n/2⌋)+n
Guess:
T(n)=O(nlogn)
Prove:
T(n)≤cnlogn (c는 적절한 양수)
Mathematical induction
- Basis or boundary conditions
- Inductive step
Bounary conditions
- Find T(n)≤cnlogn for n≥n0
- T(n)≥cnlogn for n = 1?
- T(1)=1 but c1log1=0
- n0=2, T(2)=4≤C2log2
- c≥2 and n0≥2
- T(3)에 대해서도 확인
- (3) 과정에서 찾은 c의 범위가 옳지 않을 수도 있기 때문이다.
- T(3)=2T(1)+3=5≤c3log3
- T(3)에 대해서도 c≥2가 성립한다.
- T(2)와 T(3)에 대해서 성립함을 증명했으므로 나머지는 Inductive step에서 증명한다.
Inductive step of example1
Assume that this bound holds for ⌊n/2⌋ ,
T(⌊n/2⌋)≤c⌊n/2⌋log(⌊n/2⌋).
T(n)=2T(⌊n/2⌋)+n≤2(c⌊n/2⌋log(⌊n/2⌋))+n
≤cnlog(n/2)+n
=cnlogn−cnlog2+n
=cnlogn−cn+n
≤cnlogn
(as long as c ≥ 1)
The recursion-tree method
substitution method로 증명하기 전 guess 과정에서 좋은 solution을 얻기 위해 사용
example2
Find guess using recursion tree
T(n)=3T(⌊n/4⌋)+Θ(n2)
T(n)=Θ(n2)임을 증명하자
-
Show T(n)=Ω(n2)
-
Show T(n)=O(n2)
- Guess by the recursion-tree method
- Prove by the substitution method
Show T(n)=O(n2)
n=4k, T(n)=cn2 이라고 가정하면 위 그림처럼 된다.
맨 위의 root node의 depth는 0이다.
cost computation (cost를 이용해 T(n)=O(n2)를 끌어내자)
Subproblem size for a node at depth i: n/4i
The number of nodes at depth i: 3i
The number of levels: log4n+1
cost of each depth
- except the last level: 3ic(n/4i)2=(3/16)icn2
- The last level: θ(3log4n)=θ(nlog43)
cost of all depths
T(n)=∑i=0log4n−1(163)icn2+Θ(nlog43)
<∑i=0∞(163)icn2+Θ(nlog43)
=1−(3/16)1cn2+Θ(nlog43)
=1316cn2+Θ(nlog43)
=O(n2)
prove T(n)=O(n2) by the substitution method
Show that T(n)≤dn2 (for d>0 and for the same c>0)
Recursion tree 를 통해 T(n)=θ(n2) 임을 증명했으므로 T(n)=cn2 으로 잡을 수 있다.
T(n)=3T(⌊n/4⌋)+cn2
≤3d⌊n/4⌋2+cn2
≤3d(n/4)2+cn2
=163dn2+cn2
≤dn2
where the last step holds as long as d≥1316c.
따라서 T(n)=Ω(n2) 이자 T(n)=O(n2) 이므로, T(n)=θ(n2) 이다.
example3
Given T(n)=T(n/3)+T(2n/3)+O(n), to show T(n)=O(nlgn)
recursion tree
위 그림의 tree의 최대 높이는 log23n 이다.
cost computation
the cost of each level: cn
height
n→(2/3)n→(2/3)2n→⋅⋅⋅→1=>32kn=1
when k=log23n,=>log23n
Total : each level cost x height
O(cnlog23n)=O(nlogn)
substitution method of T(n)=O(nlogn)
T(n)≤T(n/3)+T(2n/3)+cn
≤d(n/3)log(n/3)+d(2n/3)log(2n/3)+cn
=(d(n/3)logn−d(n/3)log3)+(d(2n/3)logn+d(2n/3)log(2/3))+cn
=dnlogn+d(−(n/3)log3+(2n/3)log(2/3))+cn
=dnlogn+d(−(n/3)log3+(2n/3)log2−(2n/3)log3)+cn
=dnlogn+dn(−log3+2/3)+cn
≤dnlogn,as long asd≥log3−2/3c