SlideShare a Scribd company logo
02/08/17 1
CS 332 - Algorithms
Dynamic programming
Longest Common Subsequence
02/08/17 2
Dynamic programming
It is used, when the solution can be
recursively described in terms of solutions
to subproblems (optimal substructure)
Algorithm finds solutions to subproblems
and stores them in memory for later use
More efficient than “brute-force methods”,
which solve the same subproblems over
and over again
02/08/17 3
Longest Common Subsequence
(LCS)
Application: comparison of two DNA strings
Ex: X= {A B C B D A B }, Y= {B D C A B A}
Longest Common Subsequence:
X = A B C B D A B
Y = B D C A B A
Brute force algorithm would compare each
subsequence of X with the symbols in Y
02/08/17 4
LCS Algorithm
if |X| = m, |Y| = n, then there are 2m
subsequences of x; we must compare each
with Y (n comparisons)
So the running time of the brute-force
algorithm is O(n 2m
)
Notice that the LCS problem has optimal
substructure: solutions of subproblems are
parts of the final solution.
Subproblems: “find LCS of pairs of prefixes
of X and Y”
02/08/17 5
LCS Algorithm
First we’ll find the length of LCS. Later we’ll
modify the algorithm to find LCS itself.
Define Xi, Yj to be the prefixes of X and Y of
length i and j respectively
Define c[i,j] to be the length of LCS of Xi and
Yj
Then the length of LCS of X and Y will be
c[m,n]



−−
=+−−
=
otherwise]),1[],1,[max(
],[][if1]1,1[
],[
jicjic
jyixjic
jic
02/08/17 6
LCS recursive solution
We start with i = j = 0 (empty substrings of x
and y)
Since X0 and Y0 are empty strings, their LCS is
always empty (i.e. c[0,0] = 0)
LCS of empty string and any other string is
empty, so for every i and j: c[0, j] = c[i,0] = 0



−−
=+−−
=
otherwise]),1[],1,[max(
],[][if1]1,1[
],[
jicjic
jyixjic
jic
02/08/17 7
LCS recursive solution
When we calculate c[i,j], we consider two
cases:
First case: x[i]=y[j]: one more symbol in
strings X and Y matches, so the length of LCS
Xi and Yj equals to the length of LCS of
smaller strings Xi-1 and Yi-1 , plus 1



−−
=+−−
=
otherwise]),1[],1,[max(
],[][if1]1,1[
],[
jicjic
jyixjic
jic
02/08/17 8
LCS recursive solution
Second case: x[i] != y[j]
As symbols don’t match, our solution is not
improved, and the length of LCS(Xi , Yj) is the
same as before (i.e. maximum of LCS(Xi, Yj-1)
and LCS(Xi-1,Yj)



−−
=+−−
=
otherwise]),1[],1,[max(
],[][if1]1,1[
],[
jicjic
jyixjic
jic
Why not just take the length of LCS(Xi-1, Yj-1) ?
02/08/17 9
LCS Length Algorithm
LCS-Length(X, Y)
1. m = length(X) // get the # of symbols in X
2. n = length(Y) // get the # of symbols in Y
3. for i = 1 to m c[i,0] = 0 // special case: Y0
4. for j = 1 to n c[0,j] = 0 // special case: X0
5. for i = 1 to m // for all Xi
6. for j = 1 to n // for all Yj
7. if ( Xi == Yj )
8. c[i,j] = c[i-1,j-1] + 1
9. else c[i,j] = max( c[i-1,j], c[i,j-1] )
02/08/17 10
LCS Example
We’ll see how LCS algorithm works on the
following example:
X = ABCB
Y = BDCAB
LCS(X, Y) = BCB
X = A B C B
Y = B D C A B
What is the Longest Common Subsequence
of X and Y?
02/08/17 11
LCS Example (0)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
X = ABCB; m = |X| = 4
Y = BDCAB; n = |Y| = 5
Allocate array c[5,4]
ABCB
BDCAB
02/08/17 12
LCS Example (1)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
for i = 1 to m c[i,0] = 0
for j = 1 to n c[0,j] = 0
ABCB
BDCAB
02/08/17 13
LCS Example (2)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
0
ABCB
BDCAB
02/08/17 14
LCS Example (3)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
0 0 0
ABCB
BDCAB
02/08/17 15
LCS Example (4)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
0 0 0 1
ABCB
BDCAB
02/08/17 16
LCS Example (5)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
000 1 1
ABCB
BDCAB
02/08/17 17
LCS Example (6)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
0 0 10 1
1
ABCB
BDCAB
02/08/17 18
LCS Example (7)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
1000 1
1 1 11
ABCB
BDCAB
02/08/17 19
LCS Example (8)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
1000 1
1 1 1 1 2
ABCB
BDCAB
02/08/17 20
LCS Example (10)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
1000 1
21 1 11
1 1
ABCB
BDCAB
02/08/17 21
LCS Example (11)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
1000 1
1 21 11
1 1 2
ABCB
BDCAB
02/08/17 22
LCS Example (12)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
1000 1
1 21 1
1 1 2
1
22
ABCB
BDCAB
02/08/17 23
LCS Example (13)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
1000 1
1 21 1
1 1 2
1
22
1
ABCB
BDCAB
02/08/17 24
LCS Example (14)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
1000 1
1 21 1
1 1 2
1
22
1 1 2 2
ABCB
BDCAB
02/08/17 25
LCS Example (15)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
B
Yj BB ACD
0
0
00000
0
0
0
if ( Xi == Yj )
c[i,j] = c[i-1,j-1] + 1
else c[i,j] = max( c[i-1,j], c[i,j-1] )
1000 1
1 21 1
1 1 2
1
22
1 1 2 2 3
ABCB
BDCAB
02/08/17 26
LCS Algorithm Running Time
LCS algorithm calculates the values of each
entry of the array c[m,n]
So what is the running time?
O(m*n)
since each c[i,j] is calculated in
constant time, and there are m*n
elements in the array
02/08/17 27
How to find actual LCS
So far, we have just found the length of LCS,
but not LCS itself.
We want to modify this algorithm to make it
output Longest Common Subsequence of X
and Y
Each c[i,j] depends on c[i-1,j] and c[i,j-1]
or c[i-1, j-1]
For each c[i,j] we can say how it was acquired:
2
2 3
2 For example, here
c[i,j] = c[i-1,j-1] +1 = 2+1=3
02/08/17 28
How to find actual LCS - continued
Remember that



−−
=+−−
=
otherwise]),1[],1,[max(
],[][if1]1,1[
],[
jicjic
jyixjic
jic
So we can start from c[m,n] and go backwards
Whenever c[i,j] = c[i-1, j-1]+1, remember
x[i] (because x[i] is a part of LCS)
When i=0 or j=0 (i.e. we reached the
beginning), output remembered letters in
reverse order
02/08/17 29
Finding LCS
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
Yj BB ACD
0
0
00000
0
0
0
1000 1
1 21 1
1 1 2
1
22
1 1 2 2 3B
02/08/17 30
Finding LCS (2)
j 0 1 2 3 4 5
0
1
2
3
4
i
Xi
A
B
C
Yj BB ACD
0
0
00000
0
0
0
1000 1
1 21 1
1 1 2
1
22
1 1 2 2 3B
B C BLCS (reversed order):
LCS (straight order): B C B
(this string turned out to be a palindrome)
02/08/17 31
Knapsack problem
Given some items, pack the knapsack to get
the maximum total value. Each item has some
weight and some value. Total weight that we can
carry is no more than some fixed number W.
So we must consider weights of items as well as
their value.
Item # Weight Value
1 1 8
2 3 6
3 5 5
02/08/17 32
Knapsack problem
There are two versions of the problem:
(1) “0-1 knapsack problem” and
(2) “Fractional knapsack problem”
(1) Items are indivisible; you either take an item
or not. Solved with dynamic programming
(2) Items are divisible: you can take any fraction
of an item. Solved with a greedy algorithm.

More Related Content

What's hot

minimum spanning trees Algorithm
minimum spanning trees Algorithm minimum spanning trees Algorithm
minimum spanning trees Algorithm
sachin varun
 
Vertex cover Problem
Vertex cover ProblemVertex cover Problem
Vertex cover Problem
Gajanand Sharma
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithmSrikrishnan Suresh
 
Kruskal Algorithm
Kruskal AlgorithmKruskal Algorithm
Kruskal Algorithm
Bhavik Vashi
 
Lecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular LanguagesLecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular Languages
Marina Santini
 
Bisection
BisectionBisection
Bisection
Shipon Sarder
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtrackingmandlapure
 
Approximation Algorithms
Approximation AlgorithmsApproximation Algorithms
Approximation Algorithms
Nicolas Bettenburg
 
Prim's algorithm
Prim's algorithmPrim's algorithm
Prim's algorithm
Pankaj Thakur
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programingrupali_2bonde
 
Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)
Animesh Chaturvedi
 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning tree
Hinal Lunagariya
 
01 Knapsack using Dynamic Programming
01 Knapsack using Dynamic Programming01 Knapsack using Dynamic Programming
01 Knapsack using Dynamic Programming
Fenil Shah
 
Intro automata theory
Intro automata theory Intro automata theory
Intro automata theory
Rajendran
 
simple problem to convert NFA with epsilon to without epsilon
simple problem to convert NFA with epsilon to without epsilonsimple problem to convert NFA with epsilon to without epsilon
simple problem to convert NFA with epsilon to without epsilon
kanikkk
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
Nv Thejaswini
 
Greedy Algorihm
Greedy AlgorihmGreedy Algorihm
Greedy Algorihm
Muhammad Amjad Rana
 
Activity selection problem
Activity selection problemActivity selection problem
Activity selection problem
QAU ISLAMABAD,PAKISTAN
 
Depth First Search ( DFS )
Depth First Search ( DFS )Depth First Search ( DFS )
Depth First Search ( DFS )
Sazzad Hossain
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
Rajendran
 

What's hot (20)

minimum spanning trees Algorithm
minimum spanning trees Algorithm minimum spanning trees Algorithm
minimum spanning trees Algorithm
 
Vertex cover Problem
Vertex cover ProblemVertex cover Problem
Vertex cover Problem
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithm
 
Kruskal Algorithm
Kruskal AlgorithmKruskal Algorithm
Kruskal Algorithm
 
Lecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular LanguagesLecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular Languages
 
Bisection
BisectionBisection
Bisection
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtracking
 
Approximation Algorithms
Approximation AlgorithmsApproximation Algorithms
Approximation Algorithms
 
Prim's algorithm
Prim's algorithmPrim's algorithm
Prim's algorithm
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)
 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning tree
 
01 Knapsack using Dynamic Programming
01 Knapsack using Dynamic Programming01 Knapsack using Dynamic Programming
01 Knapsack using Dynamic Programming
 
Intro automata theory
Intro automata theory Intro automata theory
Intro automata theory
 
simple problem to convert NFA with epsilon to without epsilon
simple problem to convert NFA with epsilon to without epsilonsimple problem to convert NFA with epsilon to without epsilon
simple problem to convert NFA with epsilon to without epsilon
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
 
Greedy Algorihm
Greedy AlgorihmGreedy Algorihm
Greedy Algorihm
 
Activity selection problem
Activity selection problemActivity selection problem
Activity selection problem
 
Depth First Search ( DFS )
Depth First Search ( DFS )Depth First Search ( DFS )
Depth First Search ( DFS )
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 

Viewers also liked

Longest Common Subsequence (LCS) Algorithm
Longest Common Subsequence (LCS) AlgorithmLongest Common Subsequence (LCS) Algorithm
Longest Common Subsequence (LCS) Algorithm
Darshit Metaliya
 
Longest common subsequence lcs
Longest common subsequence  lcsLongest common subsequence  lcs
Longest common subsequence lcs
Shahariar Rabby
 
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
Tosin Amuda
 
Randomized algorithms ver 1.0
Randomized algorithms ver 1.0Randomized algorithms ver 1.0
Randomized algorithms ver 1.0
Dr. C.V. Suresh Babu
 
lecture 24
lecture 24lecture 24
lecture 24sajinsc
 
The selection sort algorithm
The selection sort algorithmThe selection sort algorithm
The selection sort algorithm
David Burks-Courses
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysissumitbardhan
 
Algorithm Analysis and Design Class Notes
Algorithm Analysis and Design Class NotesAlgorithm Analysis and Design Class Notes
Algorithm Analysis and Design Class Notes
Kumar Avinash
 
Comparitive Analysis of Algorithm strategies
Comparitive Analysis of Algorithm strategiesComparitive Analysis of Algorithm strategies
Comparitive Analysis of Algorithm strategies
Talha Shaikh
 
Quick sort-Data Structure
Quick sort-Data StructureQuick sort-Data Structure
Quick sort-Data Structure
Jeanie Arnoco
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
Madhu Bala
 
DESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSDESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSGayathri Gaayu
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
Tareq Hasan
 
Algorithm analysis (All in one)
Algorithm analysis (All in one)Algorithm analysis (All in one)
Algorithm analysis (All in one)
jehan1987
 
Algorithms and Flowcharts
Algorithms and FlowchartsAlgorithms and Flowcharts
Algorithms and Flowcharts
Deva Singh
 
The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017
LinkedIn
 

Viewers also liked (19)

Longest Common Subsequence (LCS) Algorithm
Longest Common Subsequence (LCS) AlgorithmLongest Common Subsequence (LCS) Algorithm
Longest Common Subsequence (LCS) Algorithm
 
Longest common subsequence lcs
Longest common subsequence  lcsLongest common subsequence  lcs
Longest common subsequence lcs
 
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
 
Randomized algorithms ver 1.0
Randomized algorithms ver 1.0Randomized algorithms ver 1.0
Randomized algorithms ver 1.0
 
lecture 24
lecture 24lecture 24
lecture 24
 
The selection sort algorithm
The selection sort algorithmThe selection sort algorithm
The selection sort algorithm
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
 
Algorithm Analysis and Design Class Notes
Algorithm Analysis and Design Class NotesAlgorithm Analysis and Design Class Notes
Algorithm Analysis and Design Class Notes
 
Comparitive Analysis of Algorithm strategies
Comparitive Analysis of Algorithm strategiesComparitive Analysis of Algorithm strategies
Comparitive Analysis of Algorithm strategies
 
Quick sort-Data Structure
Quick sort-Data StructureQuick sort-Data Structure
Quick sort-Data Structure
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
 
DESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSDESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMS
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
 
Algorithm.ppt
Algorithm.pptAlgorithm.ppt
Algorithm.ppt
 
Writing algorithms
Writing algorithmsWriting algorithms
Writing algorithms
 
Algorithm analysis (All in one)
Algorithm analysis (All in one)Algorithm analysis (All in one)
Algorithm analysis (All in one)
 
Algorithms and Flowcharts
Algorithms and FlowchartsAlgorithms and Flowcharts
Algorithms and Flowcharts
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
 
The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017
 

Similar to Longest common subsequences in Algorithm Analysis

Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programmingklyni777
 
Longest Common Sub-sequence (LCS)
Longest Common Sub-sequence (LCS)Longest Common Sub-sequence (LCS)
Longest Common Sub-sequence (LCS)
Badrul Alam
 
Dynamic Programing_LCS.ppt
Dynamic Programing_LCS.pptDynamic Programing_LCS.ppt
Dynamic Programing_LCS.ppt
manasgaming4
 
Dynamic1
Dynamic1Dynamic1
Dynamic1MyAlome
 
Free video lectures for mca
Free video lectures for mcaFree video lectures for mca
Free video lectures for mca
Edhole.com
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Shakil Ahmed
 
17-dynprog2.ppt
17-dynprog2.ppt17-dynprog2.ppt
17-dynprog2.ppt
GGHSJANDAWALA
 
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog217-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2
Shanmuganathan C
 
A fixed point theorem for weakly c contraction mappings of integral type.
A fixed point theorem for  weakly c   contraction mappings of integral type.A fixed point theorem for  weakly c   contraction mappings of integral type.
A fixed point theorem for weakly c contraction mappings of integral type.
Alexander Decker
 
Heuristic Algorithm for Finding Sensitivity Analysis in Interval Solid Transp...
Heuristic Algorithm for Finding Sensitivity Analysis in Interval Solid Transp...Heuristic Algorithm for Finding Sensitivity Analysis in Interval Solid Transp...
Heuristic Algorithm for Finding Sensitivity Analysis in Interval Solid Transp...
AM Publications
 
CS323: Longest Common Subsequences
CS323: Longest Common SubsequencesCS323: Longest Common Subsequences
CS323: Longest Common Subsequences
Jinho Choi
 
Solucao_Marion_Thornton_Dinamica_Classic (1).pdf
Solucao_Marion_Thornton_Dinamica_Classic (1).pdfSolucao_Marion_Thornton_Dinamica_Classic (1).pdf
Solucao_Marion_Thornton_Dinamica_Classic (1).pdf
FranciscoJavierCaedo
 
Design and Implementation of Parallel and Randomized Approximation Algorithms
Design and Implementation of Parallel and Randomized Approximation AlgorithmsDesign and Implementation of Parallel and Randomized Approximation Algorithms
Design and Implementation of Parallel and Randomized Approximation Algorithms
Ajay Bidyarthy
 
Lecture8 xing
Lecture8 xingLecture8 xing
Lecture8 xing
Tianlu Wang
 
Control assignment#2
Control assignment#2Control assignment#2
Control assignment#2
cairo university
 
Ols
OlsOls
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
Krish_ver2
 
4th Semester (Dec-2015; Jan-2016) Civil Engineering Question Paper
4th Semester (Dec-2015; Jan-2016) Civil Engineering Question Paper4th Semester (Dec-2015; Jan-2016) Civil Engineering Question Paper
4th Semester (Dec-2015; Jan-2016) Civil Engineering Question Paper
BGS Institute of Technology, Adichunchanagiri University (ACU)
 

Similar to Longest common subsequences in Algorithm Analysis (20)

Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
Longest Common Sub-sequence (LCS)
Longest Common Sub-sequence (LCS)Longest Common Sub-sequence (LCS)
Longest Common Sub-sequence (LCS)
 
Dynamic programming lcs
Dynamic programming lcsDynamic programming lcs
Dynamic programming lcs
 
Dynamic Programing_LCS.ppt
Dynamic Programing_LCS.pptDynamic Programing_LCS.ppt
Dynamic Programing_LCS.ppt
 
Dynamic1
Dynamic1Dynamic1
Dynamic1
 
Free video lectures for mca
Free video lectures for mcaFree video lectures for mca
Free video lectures for mca
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
17-dynprog2.ppt
17-dynprog2.ppt17-dynprog2.ppt
17-dynprog2.ppt
 
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog217-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2
 
A fixed point theorem for weakly c contraction mappings of integral type.
A fixed point theorem for  weakly c   contraction mappings of integral type.A fixed point theorem for  weakly c   contraction mappings of integral type.
A fixed point theorem for weakly c contraction mappings of integral type.
 
Heuristic Algorithm for Finding Sensitivity Analysis in Interval Solid Transp...
Heuristic Algorithm for Finding Sensitivity Analysis in Interval Solid Transp...Heuristic Algorithm for Finding Sensitivity Analysis in Interval Solid Transp...
Heuristic Algorithm for Finding Sensitivity Analysis in Interval Solid Transp...
 
CS323: Longest Common Subsequences
CS323: Longest Common SubsequencesCS323: Longest Common Subsequences
CS323: Longest Common Subsequences
 
Solucao_Marion_Thornton_Dinamica_Classic (1).pdf
Solucao_Marion_Thornton_Dinamica_Classic (1).pdfSolucao_Marion_Thornton_Dinamica_Classic (1).pdf
Solucao_Marion_Thornton_Dinamica_Classic (1).pdf
 
Design and Implementation of Parallel and Randomized Approximation Algorithms
Design and Implementation of Parallel and Randomized Approximation AlgorithmsDesign and Implementation of Parallel and Randomized Approximation Algorithms
Design and Implementation of Parallel and Randomized Approximation Algorithms
 
Lecture8 xing
Lecture8 xingLecture8 xing
Lecture8 xing
 
Control assignment#2
Control assignment#2Control assignment#2
Control assignment#2
 
Ols
OlsOls
Ols
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
 
Ch02 6
Ch02 6Ch02 6
Ch02 6
 
4th Semester (Dec-2015; Jan-2016) Civil Engineering Question Paper
4th Semester (Dec-2015; Jan-2016) Civil Engineering Question Paper4th Semester (Dec-2015; Jan-2016) Civil Engineering Question Paper
4th Semester (Dec-2015; Jan-2016) Civil Engineering Question Paper
 

More from Rajendran

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower bounds
Rajendran
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding Costs
Rajendran
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower bounds
Rajendran
 
Red black tree
Red black treeRed black tree
Red black tree
Rajendran
 
Hash table
Hash tableHash table
Hash table
Rajendran
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statistics
Rajendran
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theorem
Rajendran
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theorem
Rajendran
 
Master method
Master method Master method
Master method
Rajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
Rajendran
 
Hash tables
Hash tablesHash tables
Hash tables
Rajendran
 
Lower bound
Lower boundLower bound
Lower bound
Rajendran
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
Rajendran
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
Rajendran
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of Quicksort
Rajendran
 
Np completeness
Np completenessNp completeness
Np completeness
Rajendran
 
computer languages
computer languagescomputer languages
computer languages
Rajendran
 
proving non-computability
proving non-computabilityproving non-computability
proving non-computability
Rajendran
 
the halting_problem
the halting_problemthe halting_problem
the halting_problem
Rajendran
 
universality
universalityuniversality
universality
Rajendran
 

More from Rajendran (20)

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower bounds
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding Costs
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower bounds
 
Red black tree
Red black treeRed black tree
Red black tree
 
Hash table
Hash tableHash table
Hash table
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statistics
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theorem
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theorem
 
Master method
Master method Master method
Master method
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Hash tables
Hash tablesHash tables
Hash tables
 
Lower bound
Lower boundLower bound
Lower bound
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of Quicksort
 
Np completeness
Np completenessNp completeness
Np completeness
 
computer languages
computer languagescomputer languages
computer languages
 
proving non-computability
proving non-computabilityproving non-computability
proving non-computability
 
the halting_problem
the halting_problemthe halting_problem
the halting_problem
 
universality
universalityuniversality
universality
 

Recently uploaded

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 

Recently uploaded (20)

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 

Longest common subsequences in Algorithm Analysis

  • 1. 02/08/17 1 CS 332 - Algorithms Dynamic programming Longest Common Subsequence
  • 2. 02/08/17 2 Dynamic programming It is used, when the solution can be recursively described in terms of solutions to subproblems (optimal substructure) Algorithm finds solutions to subproblems and stores them in memory for later use More efficient than “brute-force methods”, which solve the same subproblems over and over again
  • 3. 02/08/17 3 Longest Common Subsequence (LCS) Application: comparison of two DNA strings Ex: X= {A B C B D A B }, Y= {B D C A B A} Longest Common Subsequence: X = A B C B D A B Y = B D C A B A Brute force algorithm would compare each subsequence of X with the symbols in Y
  • 4. 02/08/17 4 LCS Algorithm if |X| = m, |Y| = n, then there are 2m subsequences of x; we must compare each with Y (n comparisons) So the running time of the brute-force algorithm is O(n 2m ) Notice that the LCS problem has optimal substructure: solutions of subproblems are parts of the final solution. Subproblems: “find LCS of pairs of prefixes of X and Y”
  • 5. 02/08/17 5 LCS Algorithm First we’ll find the length of LCS. Later we’ll modify the algorithm to find LCS itself. Define Xi, Yj to be the prefixes of X and Y of length i and j respectively Define c[i,j] to be the length of LCS of Xi and Yj Then the length of LCS of X and Y will be c[m,n]    −− =+−− = otherwise]),1[],1,[max( ],[][if1]1,1[ ],[ jicjic jyixjic jic
  • 6. 02/08/17 6 LCS recursive solution We start with i = j = 0 (empty substrings of x and y) Since X0 and Y0 are empty strings, their LCS is always empty (i.e. c[0,0] = 0) LCS of empty string and any other string is empty, so for every i and j: c[0, j] = c[i,0] = 0    −− =+−− = otherwise]),1[],1,[max( ],[][if1]1,1[ ],[ jicjic jyixjic jic
  • 7. 02/08/17 7 LCS recursive solution When we calculate c[i,j], we consider two cases: First case: x[i]=y[j]: one more symbol in strings X and Y matches, so the length of LCS Xi and Yj equals to the length of LCS of smaller strings Xi-1 and Yi-1 , plus 1    −− =+−− = otherwise]),1[],1,[max( ],[][if1]1,1[ ],[ jicjic jyixjic jic
  • 8. 02/08/17 8 LCS recursive solution Second case: x[i] != y[j] As symbols don’t match, our solution is not improved, and the length of LCS(Xi , Yj) is the same as before (i.e. maximum of LCS(Xi, Yj-1) and LCS(Xi-1,Yj)    −− =+−− = otherwise]),1[],1,[max( ],[][if1]1,1[ ],[ jicjic jyixjic jic Why not just take the length of LCS(Xi-1, Yj-1) ?
  • 9. 02/08/17 9 LCS Length Algorithm LCS-Length(X, Y) 1. m = length(X) // get the # of symbols in X 2. n = length(Y) // get the # of symbols in Y 3. for i = 1 to m c[i,0] = 0 // special case: Y0 4. for j = 1 to n c[0,j] = 0 // special case: X0 5. for i = 1 to m // for all Xi 6. for j = 1 to n // for all Yj 7. if ( Xi == Yj ) 8. c[i,j] = c[i-1,j-1] + 1 9. else c[i,j] = max( c[i-1,j], c[i,j-1] )
  • 10. 02/08/17 10 LCS Example We’ll see how LCS algorithm works on the following example: X = ABCB Y = BDCAB LCS(X, Y) = BCB X = A B C B Y = B D C A B What is the Longest Common Subsequence of X and Y?
  • 11. 02/08/17 11 LCS Example (0) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD X = ABCB; m = |X| = 4 Y = BDCAB; n = |Y| = 5 Allocate array c[5,4] ABCB BDCAB
  • 12. 02/08/17 12 LCS Example (1) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 for i = 1 to m c[i,0] = 0 for j = 1 to n c[0,j] = 0 ABCB BDCAB
  • 13. 02/08/17 13 LCS Example (2) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 0 ABCB BDCAB
  • 14. 02/08/17 14 LCS Example (3) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 0 0 0 ABCB BDCAB
  • 15. 02/08/17 15 LCS Example (4) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 0 0 0 1 ABCB BDCAB
  • 16. 02/08/17 16 LCS Example (5) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 000 1 1 ABCB BDCAB
  • 17. 02/08/17 17 LCS Example (6) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 0 0 10 1 1 ABCB BDCAB
  • 18. 02/08/17 18 LCS Example (7) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 1000 1 1 1 11 ABCB BDCAB
  • 19. 02/08/17 19 LCS Example (8) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 1000 1 1 1 1 1 2 ABCB BDCAB
  • 20. 02/08/17 20 LCS Example (10) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 1000 1 21 1 11 1 1 ABCB BDCAB
  • 21. 02/08/17 21 LCS Example (11) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 1000 1 1 21 11 1 1 2 ABCB BDCAB
  • 22. 02/08/17 22 LCS Example (12) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 1000 1 1 21 1 1 1 2 1 22 ABCB BDCAB
  • 23. 02/08/17 23 LCS Example (13) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 1000 1 1 21 1 1 1 2 1 22 1 ABCB BDCAB
  • 24. 02/08/17 24 LCS Example (14) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 1000 1 1 21 1 1 1 2 1 22 1 1 2 2 ABCB BDCAB
  • 25. 02/08/17 25 LCS Example (15) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C B Yj BB ACD 0 0 00000 0 0 0 if ( Xi == Yj ) c[i,j] = c[i-1,j-1] + 1 else c[i,j] = max( c[i-1,j], c[i,j-1] ) 1000 1 1 21 1 1 1 2 1 22 1 1 2 2 3 ABCB BDCAB
  • 26. 02/08/17 26 LCS Algorithm Running Time LCS algorithm calculates the values of each entry of the array c[m,n] So what is the running time? O(m*n) since each c[i,j] is calculated in constant time, and there are m*n elements in the array
  • 27. 02/08/17 27 How to find actual LCS So far, we have just found the length of LCS, but not LCS itself. We want to modify this algorithm to make it output Longest Common Subsequence of X and Y Each c[i,j] depends on c[i-1,j] and c[i,j-1] or c[i-1, j-1] For each c[i,j] we can say how it was acquired: 2 2 3 2 For example, here c[i,j] = c[i-1,j-1] +1 = 2+1=3
  • 28. 02/08/17 28 How to find actual LCS - continued Remember that    −− =+−− = otherwise]),1[],1,[max( ],[][if1]1,1[ ],[ jicjic jyixjic jic So we can start from c[m,n] and go backwards Whenever c[i,j] = c[i-1, j-1]+1, remember x[i] (because x[i] is a part of LCS) When i=0 or j=0 (i.e. we reached the beginning), output remembered letters in reverse order
  • 29. 02/08/17 29 Finding LCS j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C Yj BB ACD 0 0 00000 0 0 0 1000 1 1 21 1 1 1 2 1 22 1 1 2 2 3B
  • 30. 02/08/17 30 Finding LCS (2) j 0 1 2 3 4 5 0 1 2 3 4 i Xi A B C Yj BB ACD 0 0 00000 0 0 0 1000 1 1 21 1 1 1 2 1 22 1 1 2 2 3B B C BLCS (reversed order): LCS (straight order): B C B (this string turned out to be a palindrome)
  • 31. 02/08/17 31 Knapsack problem Given some items, pack the knapsack to get the maximum total value. Each item has some weight and some value. Total weight that we can carry is no more than some fixed number W. So we must consider weights of items as well as their value. Item # Weight Value 1 1 8 2 3 6 3 5 5
  • 32. 02/08/17 32 Knapsack problem There are two versions of the problem: (1) “0-1 knapsack problem” and (2) “Fractional knapsack problem” (1) Items are indivisible; you either take an item or not. Solved with dynamic programming (2) Items are divisible: you can take any fraction of an item. Solved with a greedy algorithm.