Longest Common Subsequence in C: A Dynamic Programming Approach
Longest Common Subsequence in C: A Dynamic Programming Approach
Master the Longest Common Subsequence problem with dynamic programming in C. Detailed explanations and code examples included.
Implementing the Longest Common Subsequence in C
The LCS problem can be efficiently solved using dynamic programming by breaking it down into smaller subproblems and storing the results to avoid redundant computations.
Here’s the code snippet for implementing the Longest Common Subsequence in C:
#include<stdio.h>
#include<string.h>
int i, j, m, n, c[20][20], z = 0;
char x[20], y[20], b[20][20], d[20];
void print(int i, int j) {
if (i == 0 || j == 0)
return;
if (b[i][j] == 'c') {
print(i - 1, j - 1);
d[z] = x[i - 1];
z++;
printf("%c", x[i - 1]);
} else if (b[i][j] == 'u')
print(i - 1, j);
else
print(i, j - 1);
}
void lcs() {
m = strlen(x);
n = strlen(y);
for (i = 0; i <= m; i++)
c[i][0] = 0;
for (i = 0; i <= n; i++)
c[0][i] = 0;
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++) {
if (x[i - 1] == y[j - 1]) {
c[i][j] = c[i - 1][j - 1] + 1;
b[i][j] = 'c';
} else if (c[i - 1][j] >= c[i][j - 1]) {
c[i][j] = c[i - 1][j];
b[i][j] = 'u';
} else {
c[i][j] = c[i][j - 1];
b[i][j] = 'l';
}
}
}
int main() {
int p, q, rlen = 0;
printf("Dynamic Programming: Longest Common Subsequence >>");
printf("\nEnter 1st Sequence: ");
scanf("%s", x);
printf("Enter 2nd Sequence: ");
scanf("%s", y);
lcs();
printf("\n\n ");
for (p = 0; p < n; p++)
printf(" %c ", y[p]);
printf("\n ");
for (p = 0; p < n; p++)
printf(" ---");
printf("\n");
for (p = 0; p < m; p++) {
printf(" %c |", x[p]);
for (q = 0; q < n; q++) {
printf(" %d ", c[p][q]);
}
printf("\n");
}
printf("\nThe Longest Common Subsequence is \"");
print(m, n);
printf("\"");
for (p = 0; p < 20; p++)
if (d[p] != '\0')
rlen++;
printf("\n\nLength of Longest Common Subsequence is: %d", rlen);
return 0;
}Explanation:
1. Variable Initialization: Initialize the variables for the lengths of the sequences, the DP table `c`, the direction table `b`, and the LCS result `d`.
2. User Input: Prompt the user to enter the two sequences.
3. LCS Function:
— Initialize the DP table with zeros.
— Fill the DP table based on the LCS algorithm:
— If characters match, increment the value from the diagonal.
— Otherwise, take the maximum value from the left or top cell.
4. Printing the LCS:
— The `print` function recursively constructs the LCS by following the directions stored in the `b` table.
5. Output Results:
— Print the DP table for visualization.
— Print the LCS and its length.
Conclusion
The Longest Common Subsequence problem is a fundamental exercise in dynamic programming, offering insights into efficient problem-solving techniques. By understanding and implementing this algorithm in C, you can enhance your skills in dynamic programming and tackle more complex problems with confidence. Happy coding!
Comments
Post a Comment