2019/4/10 chapter25
Backtracking and time complexity Backtracking is used to get the schedule. Time complexity O(n) if the jobs are sorted. Total time: O(n log n) including sorting. 2019/4/10 chapter25
Weighted Interval Scheduling: Bottom-Up Input: n, s1, s2, …, sn, f1, f2, …, fn, v1, v2, …, vn Sort jobs by finish times so that f1f2 … fn. Compute p(1), p(2) , …, p(n) M[0]=0; for j = 1 to n do M[j] = max { vj+m[p(j)], m[j-1]} if (M[j] == m[j-1]) then B[j]=j-1 else B[j]=p(j) /*for backtracking m=n; while ( m ≠0) { print “job m”; m=B[m]; } 2019/4/10 chapter25
Weighted Interval Scheduling: Bottom-Up Input: n, s1, s2, …, sn, f1, f2, …, fn, v1, v2, …, vn Sort jobs by finish times so that f1f2 … fn. Compute p(1), p(2) , …, p(n) M[0]=0; for j = 1 to n do M[j] = max { vj+m[p(j)], m[j-1]} if (M[j] == m[j-1]) then B[j]=j-1 else B[j]=p(j) /*for backtracking m=n; while ( m ≠0) { print “job m”; m=B[m]; } Solving recurrence equation is not required. 2019/4/10 chapter25
Interval with Maximum Sum. 2019/4/10 chapter25
2019/4/10 chapter25
Algorithm: O(n) 2019/4/10 chapter25
Int maxSum (int A[], int i, int j){ if (i==j){ maxSum(int A[], int i, int j) finds the interval [p, q] in array A[i…j] with max sum and return the interval [p, q]. Int maxSum (int A[], int i, int j){ if (i==j){ return [i, i] as the interval and A[i] as the sum } m=(i+j)/2; ([p1,q1], s1) = maxSum(A[], i, m); ([p2, q2], s2) = maxSum(A[], m+1, j); ([p3,q3], s3) = sumBothSides(A[], i, j, m) ([p, q], s) = the max of the three return [p, q} and s. 2019/4/10 chapter25
f(n)=2f(n/2)+O(n). So, f(n)=O(nlog n). Running time: f(n)=2f(n/2)+O(n). So, f(n)=O(nlog n). Open Problem: Can we design a faster algorithm? (come back later after learning other techniques) 2019/4/10
Part-D1 Binary Search Trees Dictionaries 二○一九年四月十日 Part-D1 Binary Search Trees < 6 2 > 9 1 4 = 8 Binary Search Trees
Binary Search Trees (§ 10.1) A binary search tree is a binary tree storing keys (or key-value entries) at its internal nodes and satisfying the following property: Let u, v, and w be three nodes such that u is in the left subtree of v and w is in the right subtree of v. We have key(u) key(v) key(w) External nodes do not store items An inorder traversal of a binary search trees visits the keys in increasing order 6 9 2 4 1 8 Binary Search Trees
Cost of the tree: f6*1+f2*2+f9*2+f1*3+f4*3+f8*3 < 6 2 > 9 1 4 = 8 Cost of the tree: f6*1+f2*2+f9*2+f1*3+f4*3+f8*3 2019/4/10
2019/4/10
2019/4/10
Assume that e1<e2<…en Algorithm: Assume that e1<e2<…en Calculate the sum of fi 2019/4/10
Running time: A bit disappointing??? Using a technique called memoization, we can have a polynomial time algorithm. 2019/4/10