算法导论第三天学习笔记
分治策略
递归式与分治方法是紧密相关的,因为递归式可以很自然的刻画分治算法的运行时间
求解递归式的方法
1、代入法
2、递归数法
3、主方法;T(n) = aT(n/b) + f(n), (a >= 1, b > 1).
最大子数组问题
代码1
//伪代码
FIND-MAX-CROSSING-SUBARRAY(A, low, mid, high):
left-sum = -∞
sum = 0
for i = mid downto low
sum += A[i]
if sum > left-sum
left-sum = sum
max-left = i
right-sum = -∞
sum = 0
for j = mid + 1 to high
sum += A[j]
if sum > right-sum
right-sum = sum
max-right = j
return (max-left, max-right, left-sum + right-sum)
代码2
//最大子数组分治法求解伪代码
FIND-MAXIMUM-SUBARRAY(A, low, high):
if high == low
return (low, high, A[low])
else mid = (low + high) / 2
(left-low, left-high, left-sum) = FIND-MAXIMUM-SUBARRAY(A, low, mid)
(right-low, right-high, right-sum) = FIND-MAXIMUM-SUBARRAY(A, mid + 1, right)
(cross-low, cross-high, right-sum) = FIND-MAX-CROSSING-SUBARRAY(A, low, mid, high)
if left-sum >= right-sum and left-sum >= cross-sum
return (left-low, left-high, left-sum)
else if rigth-sum >= left-usm and right-sum >= cross-sum
return (right-low, right-high, right-sum)
else
return (cross-low, cross-right, cross-sum)
代码3
//最大子数组暴力求解伪代码
FIND-MAXIMUM-SUBARRAY(A):
max = -∞
for i = 0 to A.length
sum = 0
for j = i to A.length
sum += A[j]
if sum > max
max = sum
low = i
high = j
return (low, high, max)
矩阵乘法的Strassen算法
代码4
//矩阵乘法暴力求解伪代码
SQUARE-MATRIX-MULTIPLY(A, B):
n = A.rows
let C be a new n × n matrix
for i = 1 to n
for j = 1 to n
cij = 0
for k = 1 to n
cij += aik * bkj
return C
代码5
//矩阵乘法递归分治算法伪代码
SQUARE-MATRIX-MULTIPLY-RECURSIVE(A, B):
n = A.rows
let C be a new n × n matrix
if n == 1
c11 = a11 * b11
else parition A, B, and C as in equations(4, 9)
C11 = SQUARE-MATRIX-MULTIPLY-RECURSIVE(A11, B11) + SQUARE-MATRIX-MULTIPLY-RECURSIVE(A12, B21)
C12 = SQUARE-MATRIX-MULTIPLY-RECURSIVE(A11, B12) + SQUARE-MATRIX-MULTIPLY-RECURSIVE(A12, B22)
C21 = SQUARE-MATRIX-MULTIPLY-RECURSIVE(A21, B11) + SQUARE-MATRIX-MULTIPLY-RECURSIVE(A22, B21)
C22 = SQUARE-MATRIX-MULTIPLY-RECURSIVE(A21, B12) + SQUARE-MATRIX-MULTIPLY-RECURSIVE(A22, B22)
return C
代码6
//矩阵乘法Strassen算法伪代码
STRASSEN(A, B):
n = A.rows
let C be a new n × n matrix
if n == 1
c11 = a11 * b11
else parition A, B, and C as in equations(4, 9)
S1 = B12 - B22
S2 = A11 + A12
S3 = A21 + A22
S4 = B21 - B11
S5 = A11 + A22
S6 = B11 + B22
S7 = A12 - A22
S8 = B21 - B22
S9 = A11 - A21
S10 = B11 + B12
P1 = STRASSEN(A11, S1)
P2 = STRASSEN(S2, B22)
P3 = STRASSEN(S3, B11)
P4 = STRASSEN(A22, S4)
P5 = STRASSEN(S5, S6)
P6 = STRASSEN(S7, S8)
P7 = STRASSEN(S9, S10)
C11 = P5 + P4 - P2 + P6
C12 = P1 + P2
C21 = P3 + P4
C22 = P5 + P1 - P3 - P7
return C
用代入法求解递归式
步骤:
1、猜测解的形式
2、用数学归纳法求出解中的常数,并证明解是正确的。
用主方法求解递归式
主定理:令a >= 1和b > 1是常数,f(n)是一个函数,T(n)是定义在非负整数上的递归式:T(n) = aT(n/b) + f(n)
那么T(n)有渐进下界:
1、若对某个常数ε>0有
2、若
3、若对某个常数ε>0有,且对某个常数c<1和所有足够大的n有af(n/b)<=cf(n),则
。