Test
Question 1
a
For \(n=2^m\), we have
Define \(S(m)=T\left(2^{m}\right) .\) Hence, we have:
Developping the recurrence , we obtain
For \(i=\log m\), we have:
or equivalently,
Finally, we can say that
b
As the above figure illustrates, the complexity of the recurrence is \(\sum_{i=1}^k (\frac{3}{4})^icn\), where \(k=log_4n\). The complexity=O(cn)
Question 2
\(f_7(n),f_6(n),f_1(n),f_8(n),f_n(3),f_n(5),f_4(n),f_2(n)\)
Question 3
Initial: loop=0
Input: A[], loop
def Depth(A,loop):
If A is empty, then return.
Otherwise:
set the depth of the maximum number in A as loop
loop=loop+1
Let L and R be the parts of A to the left and right of the maximum number, respectively.
Depth(L,loop)
Depth(R,loop)
Question 4
n: the num of disks
A,B,C: rods
def hanoi(n,A,B,C):
if(n==1)
#把当前递归程序的A移动到C
move(A->C)
return
else
# 进入递归
hanoi(n-1,A,C,B)
#把当前递归程序的A移动到C
move(A->C)
# 进入递归
hanoi(n-1,B,A,C)
Proof :
We can derive the recurrence complexity of the function as below
Expand it we can get :
Let \(t=n-1\), we get
Question 5
def VerifySquenceOfBST(A)
size = A.length()
if (0 == size):
return false
i = 0
while (--size):
#Post order can divide the array into two patrs. One part is always smaller than the final element. Another part is always bigger than the final element.
while (sequence[i++]<sequence[size])
while (sequence[i++]>sequence[size])
if (i < size):
return false
i = 0
return true
Question 6
We use divide and conquer to solve this problem:
- Decomposition: decompose the string into \(n\) characters \(c\) with length of 1
- Solve: judge whether the current string is a \(c\) character. If not, change it.
- Merging: we need to merge the interval modifications calculated each time, and finally calculate the total modifications,
- Good strings can be in the front and back, so we need to make statistics on the front interval and the back interval. Look at the smaller one.
- We need to find out the minimum modification number of a-good string, so we start recursion from letter a.
input:
char: a
string: The input string
r: The length of the string
l: 0
def solve(char, l, r):
if (l == r - 1):
if str[l]!=c:
return 1
else
return 0
mid = (l+r)/2
c1 = 0, c2 = 0
for (int i = l; i < mid; i=i+1):
if (str[i] != c):
c1=c1+1
for (int i = mid; i < r; i=i+1):
if (str[i] != c):
c2=C2+1
return min(c1 + go(c+1, mid, r), c2 + go(c+1, l, mid))
Question 7
The minimum \(G\) is \(log(n)\). The algorithm is illustrated as below. The main idea of the algorithm is to use divide-conquer to divide the team into two teams and switch the back half of two divided teams
input: A,B are the first and the second half of the team respectively
def Solve(A,B):
for(i=n/2;i>1;i=i/2): #We need totally log(n) games
for(j=i;j<=up(n/2);j=j*2):#Switch palyers
switch(A[back(j-i/2)],B[back(j-i/2)])