2017/7/28
chapter25
1
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.
2017/7/28
chapter25
2
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]; }
2017/7/28
chapter25
3
Weighted Interval Scheduling: Bottom-Up
Input: n, s1, s2, …, sn, f1, f2, …, fn, v1, v2, …,Solving
vn
recurrence equation is
Sort jobs by finish times so that f1f2 … fn.
not required.
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]; }
2017/7/28
chapter25
4
Interval with Maximum Sum.
2017/7/28
chapter25
5
2017/7/28
chapter25
6
Algorithm:
O(n)
2017/7/28
chapter25
7
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.
}
2017/7/28
chapter25
8
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)
2017/7/28
9
Part-D1
Binary Search Trees
6
<
2
1
9
>
4 =
Binary Search Trees
8
10
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)
• An inorder traversal of a
binary search trees visits
the keys in increasing
order
6
2
1
9
4
8
• External nodes do not
store items
Binary Search Trees
11
<
2
1
6
9
>
4 =
8
Cost of the tree: f6*1+f2*2+f9*2+f1*3+f4*3+f8*3
2017/7/28
12
2017/7/28
13
2017/7/28
14
Algorithm:
Assume that e1<e2<…en
Calculate the sum of fi
2017/7/28
15
Running time:
A bit disappointing???
Using a technique called memoization, we can
have a polynomial time algorithm.
2017/7/28
16
© Copyright 2026 Paperzz