Lecture 1 (6 Files Merged) (6 Files Merged)
Lecture 1 (6 Files Merged) (6 Files Merged)
Lecture 1
Father of Algorithms
Abu Jafar Mohammed Ibn Musa
Al khowarizmi
Material
• Lecture slides.
• Tutorials on Web.
Introduction
➢The word algorithm comes from the name of the person author
-Abu Jafar Mohammed Ibn Musa Al khowarizmi who wrote
A text book entitled-”Algorithmi de numero indorum” Now term” Algorithmi ”in the title of the book led to
the term Algorithm.
➢An algorithm is an effective method for finding out the solution for a given problem. It is a sequence of
instruction
That conveys the method to address a problem
Introduction
➢ An algorithm is a set of steps of operations to solve a problem performing calculation, data
processing, and automated reasoning tasks.
➢ An algorithm is an efficient method that can be expressed within finite amount of Time and
space.
➢ The important aspects of algorithm design include creating an efficient algorithm to solve a
problem in an efficient way using minimum time and space.
➢ To solve a problem, different approaches can be followed. Some of them can be efficient with
respect to time consumption, whereas other approaches may be memory efficient.
PROPERTIES OF ALGORITHM
2.OUTPUT: At least one quantity is produced. For each input the algorithm
produced value from specific task.
4.FINITENESS: If we trace out the instructions of an algorithm, then for all cases, the algorithm terminates after a
finite number of steps.
5.EFFECTIVENESS: Every instruction must very basic so that it can be carried out, in principle, by a person using
only pencil & paper.
➢ A well-defined computational procedure that takes some value, or set of values, as
input and produces some value, or set of values, as output.
Differences
Algorithm Program
1.At design phase 1.At Implementation phase
2.Natural language 2.written in any
programming language
3.Person should have 3.Programmer
Domain knowledge
4.Analyze 4.Testing
ALGORITHM SPECIFICATION
Algorithm can be described (Represent) in four ways.
PSEUDO-CODE CONVENTIONS
1. Comments begin with // and continue until the end of line.
3. An identifier begins with a letter. The data types of variables are not explicitly declared.
node= record
{
data type 1 data 1;
data type n data n;
node *link;
}
4. There are two Boolean values TRUE and FALSE.
Logical Operators
AND, OR, NOT
Relational Operators
<, <=,>,>=, =, !=
Here link is a pointer to the record type node. Individual data items of a record can be
accessed with → and period.
Contd…
7. The following looping statements are employed.
For, while and repeat-until While Loop:
While < condition > do
{
<statement-1>
..
..
<statement-n>
}
For Loop:
For variable: = value-1 to value-2 step step do
{
<statement-1>
.
.
.
<statement-n>
}
repeat-until:
repeat
<statement-1>
.
.
.
<statement-n>
until<condition>
Case statement:
Case
{
: <condition-1> : <statement-1>
.
.
.
: <condition-n> : <statement-n>
: else : <statement-n+1>
}
9. Input and output are done using the instructions read & write. No format is used to specify
the size of input or output quantities
10. There is only one type of procedure: Algorithm, the heading takes the form,
Algorithm Name (Parameter lists)
consider an example, the following algorithm fields & returns the maximum of n given
numbers:
1. algorithm Max(A,n)
2. // A is an array of size n
3. {
4. Result := A[1];
5. for i:= 2 to n do
6. if A[i] > Result then
7. Result :=A[i];
8. return Result;
9. }
Problem: Suppose there are 60 students in the class. How will you calculate the
number of absentees in the class?
Pseudo Approach
1.Initialize a variable called as Count to zero, absent to zero, total to 60
2.FOR EACH Student PRESENT DO the following:
Increase the Count by One
3.Then Subtract Count from total and store the result in absent
4.Display the number of absent students
Problem: Suppose there are 60 students in the class. How will you calculate the
number of absentees in the class?
Algorithmic Approach:
1.Count <- 0, absent <- 0, total <- 60
2.REPEAT till all students counted
Count <- Count + 1
3.absent <- total - Count
4.Print "Number absent is:" , absent
Need of Algorithm
1. To understand the basic idea of the problem.
2. To find an approach to solve the problem.
3. To improve the efficiency of existing techniques.
4. To understand the basic principles of designing the algorithms. To compare the
performance of the algorithm with respect to other techniques.
6. It is the best method of description without describing the implementation detail.
7. The Algorithm gives a clear description of requirements and goal of the problem
to the designer.
8. A good design can produce a good solution.
9. To understand the flow of the problem.
PERFORMANCE ANALYSIS
Performance Analysis: An algorithm is said to be efficient and fast if it take less time
to execute and consumes less memory space at run time is called Performance Analysis.
1. SPACE COMPLEXITY:
The space complexity of an algorithm is the amount of Memory Space required
by an algorithm during course of execution is called space complexity .There are three
types of space
a) Instruction space :executable program
b) Data space: Required to store all the constant and variable data space.
c) Environment: It is required to store environment information needed to resume the
suspended space.
2. TIME COMPLEXITY:
The time complexity of an algorithm is the total amount of time required by an
algorithm to complete its execution.
Algorithms
Lecture 2
Many Definitions of “Algorithm”
• An algorithm is any well-defined computational procedure that
takes some value, or set of values, as input and produces some
value, or set of values as output.
Role of “Algorithm”
Example:
• Algorithms for the same problem can be based on very different ideas
and can solve the problem with dramatically different speeds.
• Since , the last value of m is also the greatest common divisor of the
initial m and n.
while n = 0 do
r ← m mod n
m←n
n←r
return m
Middle-school procedure for computing
• Step 3 Identify all the common factors in the two prime expansions
found in Step 1 and Step 2. (If is a common factor occurring
andtimes in and , respectively, it should be repeated times.)
• Step 4 Compute the product of all the common factors and return it
as the greatest common divisor of the numbers given.
• Example:
• 24 = 2 . 2 . 2 . 3
• = 2 . 2 . 3 = 12.
Characteristics of an Algorithm
• Input
• Output
• Definiteness
• Finiteness
• Effectiveness
• Correctness
• Simplicity
• Unambiguous
• Feasibility
• Portable
• Independent
Algorithm Expectation
• Correctness:
• Algorithms must produce correct result.
Time efficiency
The actual running time depends on many factors:
• The speed of the computer: cpu (not just clock speed), I/O, etc.
• The actual data - ex. in the sequential search if the name is first
or last.
Algorithm as a Technology
• Algorithms are just like a technology. We all use latest and greatest
processors but we need to run implementations of good
algorithms on that computer in order to properly take benefits of
our money that we spent to have the latest processor.
• Example:
Algorithm as a Technology
Computer A
Computer B
• Running time grows like
• Running time grows like
• 10 billion instructions per sec
• 10 million instructions per sec
• Thus, instructions:
• Thus, instructions:
• Time taken = sec
• Time taken = sec
• It is more than 5.5 hrs
• It is under 20 mins
Algorithm as a Technology
• A faster algorithm running on a slower machine will always win for
large enough instances
Lecture 3
Lecture #2
• Mathematical Background.
Mathematical Basics
• Polynomial: Powers of n, such as n5 and = n1/2.
• Polylogarithmic: Powers of log n, such as (log n)7. We will usually write this
as log7 n.
• For example, if we let mean “asymptotically smaller” then, loga n < nb < cn
Mathematical Basics
• Logarithm Simplification: It is a good idea to first simplify terms
involving logarithms. For example, the following formulas are
useful. Here a; b; c are constants:
• Avoid using log n in exponents. The last rule above can be used to
achieve this. For example, rather than saying ,
express this as
Mathematical Basics
• Summations: they naturally arise in the analysis of iterative
algorithms. Also, more complex forms of analysis, such as
recurrences, are often solved by reducing them to summations.
Mathematical Basics
• Constant Series: For integers a and b,
for n > 0,
• If 0 < x < 1 then this is ɵ(1). If x > 1, then this is (xn), that is, the
Mathematical Basics
• Quadratic Series: For n 0,
Mathematical Basics
• Summations with general bounds: When a summation does not start
at the 1 or 0, as most of the above formulas assume, you can just split it
up into the difference of two summations. For example, for 1 a b
Insertion Sort
Running time
• Parameterize the running time by the size of the input, since short
Kinds of analyses
• Worst-case: (usually)
• Average-case: (sometimes)
many cases.)
Best case
analysis
• Always find that A[i ] ≤ key upon the first time the while loop
test is run (when i = j − 1).
• All tj are 1.
Worst case
analysis
Machine-independent time
Order of growth
• Another abstraction to ease analysis and focus on the important
features.
• Look only at the leading term of the formula for running time.
• Drop lower-order terms.
Order of growth
• But we can’t say that the worst-case running time T(n) equals n 2.
• We say that the running time is (n2) to capture the notion that the
order of growth is n2.
Asymptotic performance
Lecture 4
Lecture #3
• Merge Sort
• Recurrences
• Asymptotic notations
Merge sort
subarray A[p…r].
Divide-and-conquer approach
• Merge sort belongs to this family.
• We shall usually omit stating the base case when T(n) = Θ(1) for
Recursion tree
• Solve T(n) = 2T(n/2) + cn, where c > 0 is constant.
Recursion tree
• Solve T(n) = 2T(n/2) + cn, where c > 0 is constant.
Merge sort
• Merge sort running time is Θ(n lg n).
• EXAMPLE:
• 2n2∈O(n3) ( c = 1 and n0 = 2)
More Examples
W-notation (lower bounds)
EXAMPLE:
)c= 1, n0= 16(
W-notation
More Examples
Θ-notation (tight bounds)
Example:
Θ-notation
Theorem
f(n) = Q(g(n))
if and only if
f(n) = O(g(n))
and
f(n) = W(g(n))
o-notation
w - notation
So… Remember
Algorithms
Lecture 5
Lecture #4
• Quick sort.
• Bucket sort.
• Divide-and-conquer algorithm.
• Sorts “in place”(like insertion sort, but not like merge sort).
3.Combine:Trivial.
Partitioning subroutine
• Key: Linear-time partitioning subroutine.
Example of partitioning
0 4
5
2
3 6
Pseudo code for quick sort
• QUICKSORT(A, p, r)
If p< r
QUICKSORT(A, q+1, r)
Best-case analysis
• Counting sort:
LOOP1:
LOOP2:
LOOP3:
LOOP4:
Analysis
Analysis
Answer:
Radix sort
• Idea:
t –1digits.
Example
Sort {329,457,657,839,436,720,355}
base-2r digits.
• Example:32-bit word
• If each b-bit word is broken into r-bit pieces, each pass of counting
Algorithms
Lecture 6
Lecture #5
• Linear search
• Binary search
Linear Search
• Find an element in a an array.
Binary Search
• Find an element in a sorted array:
• Combine: Trivial.
Binary Search
• Find an element in a sorted array:
• Combine: Trivial.
Powering a number
• Problem:Compute an, where n ∈N.
• Divide-and-conquer algorithm
Powering a number
• Divide-and-conquer algorithm
• Each node has one parent and one or two children. Root
node has no parents. Leaf nodes have no children.
Example:
Step 9 - Insert 50
50 is greater than 45 but smaller than 79 and 55. So, it will be inserted as a left subtree of 55
1.First, compare the element to be searched with the root element of the tree.
2.If root is matched with the target element, then return the node's location.
3.If it is not matched, then check whether the item is less than the root element, if it is smaller
4.If it is larger than the root element, then move to the right subtree.
6.If the element is not found or not present in the tree, then return NULL.
Time Complexity:
• Best-case: to find the element at the root
Algorithms
Lecture 7
Lecture #6
• Graph Algorithms:
• Graph representation
• Shortest-path
Graphs
• Graph G = (V, E)
• V = set of vertices
• E = set of edges (VV)
• Types of graphs
• Undirected: edge (u, v) = (v, u); for all v, (v, v) E (No self loops.)
• Directed: (u, v) is edge from u to v, denoted as u v. Self loops
are allowed.
• Weighted: each edge has an associated weight, given by a weight
function w : E R.
Representations of graphs
• Let G = (V, E), |V| = n and |E|=m
• The adjacency matrix of G written A(G), is the
n-by-n matrix in which entry ai,j is the number of
edges in G with endpoints {vi, vj}.
w w x y z
b w 0 1 1 0
y z x 1 0
a c 2 0
e
d
y 1 2 0 1
x
z 0 0 1 0
Representations of graphs
• Let G = (V, E), |V| = n and |E|=m
• The incidence matrix M(G) is the n-by-m matrix
in which entry mi,j is 1 if vi is an endpoint of ei
and otherwise is 0.
w a b c d e
b w 1 1 0 0 0
y
a c z x 1 0 1 1 0
e
x d y 0 1 1 1 1
z 0 0 0 0 1
Representations of graphs
e2 v3
v4
• Adjacency matrix e3
v5 v4 v3 v2 v1 e4 e5
v5
v1 v2
0 0 0 1 2
e1 e6
1 0 1 0 1 v2 v1
2 0 0 1 0 v3
0 0 0 0 0 v4
0 0 2 1 0 v5
Representations of graphs
e2 v3
v4
e3
e4 e5
v5
v2
• Incidence matrix
e1 e6
e6 e5 e4 e3 e2 e1 v1
2 0 0 0 0 1 v1
0 0 1 0 1 1 v2
0 1 0 1 1 0 v3
0 0 0 0 0 0 v4
0 1 1 1 0 0 v5
Graph-searching Algorithms
• Searching a graph:
• Systematically follow the edges of a graph
to visit the vertices of the graph.
• Output:
• d[v] = distance (smallest # of edges, or shortest path) from s to v, for
all v V. d[v] = if v is not reachable from s. V.
Intro 10
pseudo-code
BFS Set all nodes to "not visited";
q = new Queue();
q.enqueue(initial node);
while ( q ≠ empty ) do
{
x = q.dequeue();
Rule 2 − Insert all adjacent nodes (to removed one) into queue.
Intro 12
Example (BFS)
r s t u
0
v w x y
Q: s
0
Intro 13
Example (BFS)
r s t u
1 0
1
v w x y
Q: w r
1 1
Intro 14
Example (BFS)
r s t u
1 0 2
1 2
v w x y
Q: r t x
1 2 2
Intro 15
Example (BFS)
r s t u
1 0 2
2 1 2
v w x y
Q: t x v
2 2 2
Intro 16
Example (BFS)
r s t u
1 0 2 3
2 1 2
v w x y
Q: x v u
2 2 3
Intro 17
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: v u y
2 3 3
Intro 18
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: u y
3 3
Intro 19
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
Q: y
3
Intro 20
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
Q:
Intro 21
Example (BFS)
r s t u
1 0 2 3
2 1 2 3
v w x y
BF Tree
Intro 22
Analysis of BFS
• Initialization takes O(V).
• Traversal Loop
• After initialization, each vertex is enqueued and dequeued at most once,
and each operation takes O(1). So, total time for queuing is O(V).
• The adjacency list of each vertex is scanned at most once. The sum of
lengths of all adjacency lists is (E).
u x
v y
w z
Intro 24
Example 2
• Show the BFS tree for the following graph starting from u:
Q:
u 0 1 x u
v,x
x
x,y
v 1 2 y y
w
z
w 3 4 z
BF Tree
Intro 25
BFS(G,s)
BFS(G,s)
foreach
1.1.for eachvertex
vertexuuininV[G]
V[G]–– {s}
{s}
Another pseudo-code
22 do color[u]
docolor[u] white
white
33 d[u]d[u]
44 [u] white: undiscovered
[u]nil
nil
gray: discovered
55 color[s] gray
color[s] gray black: finished
d[s]
66 d[s] 00
77 [s]
[s]nil
nil
Q: a queue of discovered
88 QQ vertices
99 enqueue(Q,s)
enqueue(Q,s) color[v]: color of v
d[v]: distance from s to v
10
10 whileQQ
while
[u]: predecessor of v
11
11 douu
do dequeue(Q)
dequeue(Q)
12
12 foreach
for eachvvininAdj[u]
Adj[u]
13
13 do if color[v] =white
do if color[v] = white
14
14 then color[v]
thencolor[v] gray
gray
15
15 d[v]
d[v] d[u] +11
d[u] +
16
16 [v]
[v]
uu
17
17 enqueue(Q,v)
enqueue(Q,v)
18
18 color[u]
color[u] black
black
Intro 26
Depth-first Search (DFS)
• Explore edges out of the most recently discovered
vertex v.
• When all edges of v have been explored, backtrack to
explore other edges leaving the vertex from which v
was discovered (its predecessor).
• “Search as deep as possible first.”
• Continue until all vertices reachable from the original
source are discovered.
• If any undiscovered vertices remain, then one of them
is chosen as a new source and search is repeated from
that source.
Intro 27
Intro 28
Algorithms
Lecture 8
Dijkstra's algorithm
Author : Edsger Wybe Dijkstra
http://www.cs.utexas.edu/~EWD/
2
Edsger Wybe Dijkstra
- May 11, 1930 – August 6, 2002
Dijkstra's algorithm
Dijkstra's algorithm - is a solution to the single-source
shortest path problem in graph theory.
Approach: Greedy
8
Dijkstra Animated Example
10
11
Dijkstra Animated Example
12
13
14
Dijkstra Animated Example
15
16
O(|V|^2 + |E|)
18
Algorithms
Lecture 9
2
Algorithm Characteristics
• Both Prim’s and Kruskal’s Algorithms work
with undirected graphs.
• Both work with weighted and unweighted
graphs but are more interesting when edges
are weighted
• Both are greedy algorithms that produce
optimal solutions
Kruskal’s Algorithm
Walk-Through
Consider an undirected, weight graph
3
10
F C
A 4
4
3
8
6
5
4
B D
4
H 1
2
3
G 3
E
5
Sort the edges by increasing edge weight
3
10
F C edge dv edge dv
A 4
4
3 (D,E) 1 (B,E) 4
8
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
A 4 3 (D,E) 1 (B,E) 4
8 4
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
A 4 3 (D,E) 1 (B,E) 4
8 4
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
8
Select first |V|–1 edges which do not
generate a cycle
3
10
F C edge dv edge dv
A 4 3 (D,E) 1 (B,E) 4
8 4
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
A 4 3 (D,E) 1 (B,E) 4
8 4
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
10
A 4 3 (D,E) 1 (B,E) 4
8 4
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
11
Select first |V|–1 edges which do not
generate a cycle
3
10
F C edge dv edge dv
A 4 3 (D,E) 1 (B,E) 4
8 4
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
12
A 4 3 (D,E) 1 (B,E) 4
8 4
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
13
A 4 3 (D,E) 1 (B,E) 4
8 4
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
14
Select first |V|–1 edges which do not
generate a cycle
3
10
F C edge dv edge dv
A 4 3 (D,E) 1 (B,E) 4
8 4
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
15
A 4 3 (D,E) 1 (B,E) 4
8 4
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
16
A 4 3 (D,E) 1 (B,E) 4
8 4
6 (D,G) 2 (B,F) 4
5
4
B D (E,G) 3 (B,H) 4
4
H 1 (C,D) 3 (A,H) 5
2
3 (G,H) 3 (D,F) 6
G 3
E (C,F) 3 (A,B) 8
(B,C) 4 (A,F) 10
17
Select first |V|–1 edges which do not
generate a cycle
3
F C edge dv edge dv
A 3 (D,E) 1 (B,E) 4
4
(D,G) 2 (B,F) 4
5
B D (E,G) 3 (B,H) 4
H 1 (C,D) 3 (A,H) 5
2
}
3 (G,H) 3 (D,F) 6
not
G E (C,F) 3 (A,B) 8 considered
(B,C) 4 (A,F) 10
Done
Total Cost = dv = 21
18
Algorithms
Lecture 10
Lecture #9
• Greedy Algorithms.
• Making Change.
• Task Scheduling.
The Greedy Method Technique
• wi - a positive weight
• Objective:
maximize b (x / w )
iS
i i i
• Constraint: x
iS
i W
Example 2
• Given: A set S of n items, with each item i having
• bi - a positive benefit
• wi - a positive weight
Algorithm fractionalKnapsack(S, W)
xi 0
while w < W
xi min{wi , W - w}
w w + min{wi , W - w}
The Fractional Knapsack Algorithm
• Greedy choice: Keep taking item with highest value (benefit to
weight ratio)
• Since b ( x / w ) (b / w ) x
iS
i i i
iS
i i i
Machine 3
Machine 2
Machine 1
1 2 3 4 5 6 7 8 9
Algorithm taskSchedule(T)
schedule i on machine j
else
mm+1
schedule i on machine m
Task Scheduling Algorithm
• Greedy choice: consider tasks by their start time and use as few
machines as possible with this order.
• Run time: O(n log n).
Example3
• Given: a set T of n tasks, each having:
• A start time, si
Machine 3
Machine 2
Machine 1
1 2 3 4 5 6 7 8 9
Lecture 11
Lecture 10
• Basic Technique.
• Area of Applications.
• Examples.
Overlapping Subproblems
Optimal Substructure
• Notice that previous table locations also contain valid (optimal) sub-
problem solutions
Example
different states. The possible choices are shown in the figure below.
7
B E 1
4
6 4 H 3
2 3
4 6
A C 2 F J
4 3
3 4
4 3 3 I
1
D 3 G
Example
should take.
Solution: E or F
11 4 H
7
B E 1 J
4 3
C or D 6 4 H
11 2 I 3
7 3 E 7
4 6
A C 2 F J
4 3
3 4
4 3 3 I
1
D 3 G 4 J
E or
8 F 6 H
Solution:
Thus the optimum route will be
C E H
A J
D F I
i.e. A C E H J
or A D E H J with optimum
value 11.
or A D F I J
Problem Formulation
Thus
Fn ( xn ) min f n ( xn , yn ) f n ( xn , yn* )
where
fn (xn, yn) = immediate cost (stage n) +
minimum future cost (stages n+1 onward)
cxn , yn Fn 1 ( xn 1 )
choice of yn.
Characteristics of DP problems
model:
Knapsack Problem
• Value and mass of each item is
given.
• Maximize profit.
• Subject to mass constraint of
knapsack: 15 kg.
• Being a smart kid,
you apply dynamic programming
Knapsack Problem
• Given: A set S of n items, with each item i having
– wi - a positive weight
– bi - a positive benefit
• Goal: Choose items with maximum total benefit but with weight at most
W.
• If we are not allowed to take fractional amounts, then this is the 0/1
knapsack problem.
– Constraint: iT
w W i
Knapsack Problem
Example 1:
“knapsack”
Items:
1 2 3 4 5 box of width 9 in
Weight: 4 in 2 in 2 in 6 in 2 in Solution:
Benefit: $20 $3 $6 $25 $80 • item 5 ($80, 2 in)
• item 3 ($6, 2in)
• item 1 ($20, 4in)
Knapsack Problem
B[k 1, w] if wk w
B[k , w]
max{B[k 1, w], B[k 1, w wk ] bk } else
• Pseudo code:
Algorithm 01Knapsack(S, W):
Input: set S of n items with benefit bi
and weight wi; maximum weight W
Output: benefit of best subset of S with
weight at most W
let A and B be arrays of length W + 1
for w 0 to W do
B[w] 0
O(n*W)
for k 1 to n do
copy array B into array A
for w wk to W do
if A[wwk] bk > A[w] then
B[w] A[wwk] bk
return B[W]
Knapsack Problem
• Pseudo code:
Algorithm ALG(S, W):
let A and B be arrays of length W + 1
for w 0 to W do
B[w] 0
for i = 1 : n do
copy array B into array A
for j = wi : W do
O(n*W) if A[ jwi] bi > A[j] then
B[j] A[jwi] bj
return B[W]
Knapsack Problem
Weight
• Example 1 solution:
k Items 1 2 3 4 5 6 7 8 9
bk/wk
0 0/0 0 0 0 0 0 0 0 0 0
Example 1 Solution:
“knapsack”
Items:
1 2 3 4 5 box of width 9 in
Weight: 4 in 2 in 2 in 6 in 2 in
Benefit: $20 $3 $6 $25 $80 Solution:
Knapsack Problem