SEP- ADA

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6 PROGRAM 7

PART B

PROGRAM B1 PROGRAM B2 PROGRAM B3 PROGRAM B4 PROGRAM B5 PROGRAM B6 PROGRAM B7 . . .

t

 
  
 PART- B 
PROGRAM - 4
4. implement a Dynamic Programming algorithm for the Longest Common Subsequence 

#include < stdio.h>
#include < string.h>

#define MAX_LEN 100

// Function to find the maximum of two integers
int max(int a, int b) {
    return (a > b) ? a : b;
}

// Function to compute and print the LCS
void findLCS(char X[], char Y[]) {
    int m = strlen(X);
    int n = strlen(Y);

    // DP table where dp[i][j] stores the length of LCS of X[0..i-1] and Y[0..j-1]
    int dp[m + 1][n + 1];

    // Build the DP table in a bottom-up manner
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0 || j == 0) {
                dp[i][j] = 0; // Base case: empty string has LCS of length 0
            } else if (X[i - 1] == Y[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1; // Characters match
            } else {
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); // Characters don't match
            }
        }
    }

    // Length of the Longest Common Subsequence
    int lcsLength = dp[m][n];
    printf("\nLength of LCS: %d\n", lcsLength);

    // Reconstruct the LCS string by backtracking from dp[m][n]
    char lcs[lcsLength + 1];
    lcs[lcsLength] = '\0'; // Null-terminate the string

    int i = m, j = n;
    int index = lcsLength - 1;

    while (i > 0 && j > 0) {
        // If current characters match, they are part of LCS
        if (X[i - 1] == Y[j - 1]) {
            lcs[index] = X[i - 1];
            i--;
            j--;
            index--;
        }
        // If not, move in the direction of the larger DP value
        else if (dp[i - 1][j] > dp[i][j - 1]) {
            i--;
        } else {
            j--;
        }
    }

    printf("Longest Common Subsequence: %s\n", lcs);
}

int main() {
    char X[MAX_LEN], Y[MAX_LEN];

    printf("Enter first string: ");
    scanf("%s", X);

    printf("Enter second string: ");
    scanf("%s", Y);

    findLCS(X, Y);

    return 0;
}



OUTPUT
Enter first string: AGGTAB
Enter second string: GXTXAYB

Length of LCS: 4
Longest Common Subsequence: GTAB