Algorithm of Longest Common SequenceLCSLENGTH (X, Y) 1. m ← length [X] 2. n ← length [Y] 3. for i ← 1 to m 4. do c [i,0] ← 0 5. for j ← 0 to m 6. do c [0,j] ← 0 7. for i ← 1 to m 8. do for j ← 1 to n 9. do if x_{i}= y_{j} 10. then c [i,j] ← c [i1,j1] + 1 11. b [i,j] ← "↖" 12. else if c[i1,j] ≥ c[i,j1] 13. then c [i,j] ← c [i1,j] 14. b [i,j] ← "↑" 15. else c [i,j] ← c [i,j1] 16. b [i,j] ← "← " 17. return c and b. Example of Longest Common SequenceExample: Given two sequences X [1...m] and Y [1.....n]. Find the longest common subsequences to both. here X = (A,B,C,B,D,A,B) and Y = (B,D,C,A,B,A) m = length [X] and n = length [Y] m = 7 and n = 6 Here x_{1}= x [1] = A y_{1}= y [1] = B x_{2}= B y_{2}= D x_{3}= C y_{3}= C x_{4}= B y_{4}= A x_{5}= D y_{5}= B x_{6}= A y_{6}= A x_{7}= B Now fill the values of c [i, j] in m x n table Initially, for i=1 to 7 c [i, 0] = 0 For j = 0 to 6 c [0, j] = 0 That is: Now for i=1 and j = 1 x_{1} and y_{1} we get x_{1} ≠ y_{1} i.e. A ≠ B And c [i1,j] = c [0, 1] = 0 c [i, j1] = c [1,0 ] = 0 That is, c [i1,j]= c [i, j1] so c [1, 1] = 0 and b [1, 1] = ' ↑ ' Now for i=1 and j = 2 x_{1} and y_{2} we get x_{1} ≠ y_{2} i.e. A ≠ D c [i1,j] = c [0, 2] = 0 c [i, j1] = c [1,1 ] = 0 That is, c [i1,j]= c [i, j1] and c [1, 2] = 0 b [1, 2] = ' ↑ ' Now for i=1 and j = 3 x_{1} and y_{3} we get x_{1} ≠ y_{3} i.e. A ≠ C c [i1,j] = c [0, 3] = 0 c [i, j1] = c [1,2 ] = 0 so c [1,3] = 0 b [1,3] = ' ↑ ' Now for i=1 and j = 4 x_{1} and y_{4} we get. x_{1}=y_{4} i.e A = A c [1,4] = c [11,41] + 1 = c [0, 3] + 1 = 0 + 1 = 1 c [1,4] = 1 b [1,4] = ' ↖ ' Now for i=1 and j = 5 x_{1} and y_{5} we get x_{1} ≠ y_{5} c [i1,j] = c [0, 5] = 0 c [i, j1] = c [1,4 ] = 1 Thus c [i, j1] > c [i1,j] i.e. c [1, 5] = c [i, j1] = 1. So b [1, 5] = '←' Now for i=1 and j = 6 x_{1} and y_{6} we get x_{1}=y_{6} c [1, 6] = c [11,61] + 1 = c [0, 5] + 1 = 0 + 1 = 1 c [1,6] = 1 b [1,6] = ' ↖ ' Now for i=2 and j = 1 We get x_{2} and y_{1} B = B i.e. x_{2}= y_{1} c [2,1] = c [21,11] + 1 = c [1, 0] + 1 = 0 + 1 = 1 c [2, 1] = 1 and b [2, 1] = ' ↖ ' Similarly, we fill the all values of c [i, j] and we get Step 4: Constructing an LCS: The initial call is PRINTLCS (b, X, X.length, Y.length) PRINTLCS (b, x, i, j) 1. if i=0 or j=0 2. then return 3. if b [i,j] = ' ↖ ' 4. then PRINTLCS (b,x,i1,j1) 5. print x_i 6. else if b [i,j] = ' ↑ ' 7. then PRINTLCS (b,X,i1,j) 8. else PRINTLCS (b,X,i,j1) Example: Determine the LCS of (1,0,0,1,0,1,0,1) and (0,1,0,1,1,0,1,1,0). Solution: let X = (1,0,0,1,0,1,0,1) and Y = (0,1,0,1,1,0,1,1,0). We are looking for c [8, 9]. The following table is built. From the table we can deduct that LCS = 6. There are several such sequences, for instance (1,0,0,1,1,0) (0,1,0,1,0,1) and (0,0,1,1,0,1)
Next Topic0/1 Knapsack Problem

Ansible
Mockito
Talend
Azure
SharePoint
Powershell
Kali Linux
OpenCV
Kafka
Pandas
Joomla
Reinforcement