1.2 Five Representative Problems
1.2 Five Representative Problems
h Time
0 1 2 3 4 5 6 7 8 9 10 11
2
Weighted Interval Scheduling
Input. Set of jobs with start times, finish times, and weights.
Goal. Find maximum weight subset of mutually compatible jobs.
23
12
20
26
13
20
11
16 Time
0 1 2 3 4 5 6 7 8 9 10 11
3
Bipartite Matching
A 1
B 2
C 3
D 4
E 5
4
Independent Set
Input. Graph.
Goal. Find maximum cardinality independent set.
subset of nodes such that no two
joined by an edge
1 2
4 5
3
6 7
5
Competitive Facility Location
10 1 5 15 5 1 5 1 15 10
6
Five Representative Problems
7
Polynomial-Time
8
Worst-Case Analysis
9
Worst-Case Polynomial-Time
Exceptions.
Some poly-time algorithms do have high constants and/or
exponents, and are useless in practice.
Some exponential-time (or worse) algorithms are widely used
because the worst-case instances seem to be rare.
simplex method
Unix grep
10
Why It Matters
11
2.2 Asymptotic Order of Growth
Asymptotic Order of Growth
13
Notation
14
Properties
Transitivity.
If f = O(g) and g = O(h) then f = O(h).
If f = Ω(g) and g = Ω(h) then f = Ω(h).
If f = Θ(g) and g = Θ(h) then f = Θ(h).
Additivity.
If f = O(h) and g = O(h) then f + g = O(h).
If f = Ω(h) and g = Ω(h) then f + g = Ω(h).
If f = Θ(h) and g = O(h) then f + g = Θ(h).
15
Asymptotic Bounds for Some Common Functions
16
2.4 A Survey of Common Running Times
Linear Time: O(n)
18
Linear Time: O(n)
i = 1, j = 1
while (both lists are nonempty) {
if (ai ≤ bj) append ai to output list and increment i
else(ai ≤ bj)append bj to output list and increment j
}
append remainder of nonempty list to output list
O(n log n) solution. Sort the time-stamps. Scan the sorted list in
order, identifying the maximum gap between successive time-
stamps.
20
Quadratic Time: O(n2)
Closest pair of points. Given a list of n points in the plane (x1, y1),
…, (xn, yn), find the pair that is closest.
Remark. Ω(n2) seems inevitable, but this is just an illusion. see chapter 5
21
Cubic Time: O(n3)
22
Polynomial Time: O(nk) Time
Check whether S is an independent set = O(k2).
Number of k element subsets =⎛n ⎞ n (n −1) (n − 2) L (n − k +1) nk
⎜ ⎟= ≤
O(k2 nk / k!) = O(nk). ⎝ ⎠
k k (k −1) (k − 2) L (2) (1) k!
poly-time for k=17,
but not practical
23
Exponential Time
S* ← φ
foreach subset S of nodes {
check whether S in an independent set
if (S is largest independent set seen so far)
update S* ← S
}
}
24
Chapter 5
Divide and
Conquer
25
Divide-and-Conquer
Divide-and-conquer.
Break up problem into several parts.
Solve each part recursively.
Combine solutions to sub-problems into overall solution.
Consequence.
Brute force: n2.
Divide-and-conquer: n log n. Divide et impera.
Veni, vidi, vici.
- Julius Caesar
26
5.1 Mergesort
Sorting
Mergesort.
Divide array into two halves.
Recursively sort each half.
Merge two halves to make sorted whole.
A L G O R I T H M S
A L G O R I T H M S divide O(1)
A G L O R H I M S T sort 2T(n/2)
A G H I L M O R S T merge O(n)
29
Merging
A G L O R H I M S T
A G H I
30