GEN-SOLUTION(pre, C, i, j) if C[i, j] == 0 return ∅ else return {a_k} ∪ GEN-SOLUTION(pre, C, i, k) ∪ GEN-SOLUTION(pre, C, k, j)
DYNAMIC-PROGRAMMING-ACTIVITY-SELECTOR(s, f, n) // pre 表示状态转移到何处。 let pre[0 : n + 1, 0 : n + 1] and c[0 : n + 1, 0 : n + 1] be new tablges INSERT(s, +∞) for i = 0 to n c[i, i] = 0 c[i, i + 1] = 0 c[n + 1, n + 1] = 0 for l = 2 to n + 1 for i = 0 to n + 2 - l j = i + l - 1 k = i + 1 while k < j and f[k] <= s[j] if f[i] <= s[k] and c[i, k] + c[k, j] + 1 > c[i, j] c[i, j] = c[i, k] + c[k, j] + 1 pre[i, j] = k k = k + 1 return GEN-SOLUTION(pre, C, 0, n + 1)
ACTIVITY-ARRANGER(s, f, n) let A be a new array count = 0 // 使用一个二叉查找树T来存储三元组(f, hall),分别代表编号为hall的厅中,最后一个活动的结束时间为f,这个二叉查找树将以f作为键。 let T be a new ordered-set for i = 1 to n // 找到最晚能够早于s[i]结束的一个厅。 get the greatest node x in T such that x.f <= s[i] // 找不到这样的厅,需要新开。 if x == NIL INSERT(A, ∅) count = count + 1 A[count] = A[count] ∪ {a_i} let p be a new node, p.f = f[i], p.hall = count INSERT(T, p) else DELETE(T, x) A[x.hall] = A[x.hall] ∪ {a_i} x.f = f[i] INSERT(T, x) return count, A
// a_0 = (0, 0, 0),即第0个活动是没有价值的。 ACTIVITY-SELECTOR-VALUE'(s, f, v, n) // 已经假设所有活动按结束时间f进行排序。 let g[0 : n], pre[1 : n] be new arrays g[0] = 0 // p是取得最大值的下标。 p = 0 for i = 1 to n g[i] = 0 j = 0 while j < i and f[j] <= s[i] if f[j] <= s[i] and g[j] + v[i] > g[i] g[i] = g[j] + v[i] pre[i] = j j = j + 1 if g[i] > g[p] p = i A = {a_p} q = p while pre[p] != 0 A = A ∪ {A_pre[p]} p = pre[p] return g[q], A