Loading…
DAA · Dynamic programming · Program 14 · In the record
Write a program in c to find the longest common subsequence (LCS) of two sequences using dynamic programming and find its execution time using the time function.
Algorithm: LCS-Length(X, Y, m, n) 1. Start 2. For i <- 1 to m do 3. c[i][0] <- 0 4. For j <- 0 to n do 5. c[0][j] <- 0 6. For i <- 1 to m do 7. For j <- 1 to n do 8. if X[i] == Y[j] then 9. c[i][j] <- c[i-1][j-1] + 1 10. b[i][j] <- 'D' 11. else if c[i-1][j] >= c[i][j-1] then 12. c[i][j] <- c[i-1][j] 13. b[i][j] <- 'U' 14. else 15. c[i][j] <- c[i][j-1] 16. b[i][j] <- 'L' 17. print "Length of LCS" c[m][n] 18. PrintLCS(b, X, m, n) 19. Stop Algorithm: PrintLCS(b, X, i, j) 1. If (i == 0 or j == 0) then 2. Return 3. If b[i][j] == 'D' then 4. PrintLCS(b, X, i-1, j-1) 5. print X[i] 6. else if b[i][j] == 'U' then 7. PrintLCS(b, X, i-1, j) 8. else 9. PrintLCS(b, X, i, j-1)
1#include<stdio.h>2#include<string.h>3#include<time.h>4 5int c[50][50];6char b[50][50];7char x[50],y[50];8 9void printLCS(int i,int j) {10 if(i==0 || j==0)11 return;12 if(b[i][j]=='D') {13 printLCS(i-1,j-1);14 printf("%c",x[i-1]);15 }16 else if(b[i][j]=='U')17 printLCS(i-1,j);18 else19 printLCS(i,j-1);20}21 22int main() {23 int m,n,i,j,count=0;24 printf("Enter the first sequence X:");25 scanf("%s",x);26 printf("Enter the second sequence Y:");27 scanf("%s",y);28 m=strlen(x);29 n=strlen(y);30 31 clock_t start=clock();32 for(i=1;i<=m;i++)33 c[i][0]=0;34 for(j=0;j<=n;j++)35 c[0][j]=0;36 for(i=1;i<=m;i++) {37 for(j=1;j<=n;j++) {38 count++;39 if(x[i-1]==y[j-1]) {40 c[i][j]=c[i-1][j-1]+1;41 b[i][j]='D';42 }43 else if(c[i-1][j]>=c[i][j-1]) {44 c[i][j]=c[i-1][j];45 b[i][j]='U';46 }47 else {48 c[i][j]=c[i][j-1];49 b[i][j]='L';50 }51 }52 }53 clock_t end=clock();54 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;55 56 printf("\nc[i,j] table (D=diagonal, U=up, L=left):\n\t\t");57 for(j=0;j<n;j++)58 printf("%c\t",y[j]);59 for(i=0;i<=m;i++) {60 printf("\n");61 if(i==0)62 printf("\t");63 else64 printf("%c\t",x[i-1]);65 for(j=0;j<=n;j++)66 if(i==0 || j==0)67 printf("%d\t",c[i][j]);68 else69 printf("%d%c\t",c[i][j],b[i][j]);70 }71 printf("\nLength of LCS:%d",c[m][n]);72 printf("\nLCS:");73 printLCS(m,n);74 printf("\nNumber of comparisons:%d",count);75 printf("\nTime taken:%f seconds",time_taken);76 printf("\nTime complexity: O(mn)");77 printf("\nSpace complexity: O(mn)");78 printf("\n");79 return 0;80}ABCBDAB ⏎ BDCABAEnter the first sequence X:ABCBDAB Enter the second sequence Y:BDCABA c[i,j] table (D=diagonal, U=up, L=left): B D C A B A 0 0 0 0 0 0 0 A 0 0U 0U 0U 1D 1L 1D B 0 1D 1L 1L 1U 2D 2L C 0 1U 1U 2D 2L 2U 2U B 0 1D 1U 2U 2U 3D 3L D 0 1U 2D 2U 2U 3U 3U A 0 1U 2U 2U 3D 3U 4D B 0 1D 2U 2U 3U 4D 4U Length of LCS:4 LCS:BCBA Number of comparisons:42 Time taken:0.000002 seconds Time complexity: O(mn) Space complexity: O(mn)
Run program 14 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.