Created
July 31, 2026 16:04
-
-
Save raiyansarker/cb5ee760144c33afd87198ab5286c4ae to your computer and use it in GitHub Desktop.
LCS, LIS in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <string.h> | |
| char a[100]; | |
| char b[100]; | |
| void trace(int n, char t[][n + 1], int i, int j) { | |
| if (t[i][j] == 'u') { | |
| trace(n, t, i - 1, j); | |
| } else if (t[i][j] == 'l') { | |
| trace(n, t, i, j - 1); | |
| } else if (t[i][j] == 'c') { | |
| trace(n, t, i - 1, j - 1); | |
| printf("%c", a[i - 1]); | |
| } | |
| } | |
| int main() { | |
| scanf("%s %s", &a, &b); | |
| int m = strlen(a), n = strlen(b); | |
| int c[m + 1][n + 1]; | |
| char t[m + 1][n + 1]; | |
| for (int i = 0; i <= m; i++) { | |
| for (int j = 0; j <= n; j++) { | |
| c[i][j] = 0; | |
| t[i][j] = '#'; | |
| } | |
| } | |
| for (int i = 1; i <= m; i++) { | |
| for (int j = 1; j <= n; j++) { | |
| if (a[i - 1] == b[j - 1]) { | |
| c[i][j] = c[i-1][j-1] + 1; | |
| t[i][j] = 'c'; | |
| } | |
| else if (c[i - 1][j] > c[i][j - 1]) { | |
| c[i][j] = c[i - 1][j]; | |
| t[i][j] = 'u'; | |
| } | |
| else { | |
| c[i][j] = c[i][j-1]; | |
| t[i][j] = 'l'; | |
| } | |
| } | |
| } | |
| trace(n, t, m, n); | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <limits.h> | |
| void trace(int arr[], int prev[], int i) { | |
| if (prev[i] == -1) { | |
| printf("%d ", arr[i]); | |
| return; | |
| } | |
| trace(arr, prev, prev[i]); | |
| printf("%d ", arr[i]); | |
| } | |
| int main() | |
| { | |
| int n; scanf("%d", &n); | |
| int arr[n]; | |
| int l[n]; | |
| int prev[n]; | |
| for (int i = 0; i < n; i++) { | |
| scanf("%d", &arr[i]); | |
| l[i] = 1; | |
| prev[i] = -1; | |
| } | |
| int max = INT_MIN, max_index = -1; | |
| for (int i = 1; i < n; i++) { | |
| for (int j = 0; j < i; j++) { | |
| if (arr[i] > arr[j] && l[j] + 1 > l[i]) { | |
| l[i] = l[j] + 1; | |
| prev[i] = j; | |
| } | |
| if (l[i] > max) { | |
| max = l[i]; | |
| max_index = i; | |
| } | |
| } | |
| } | |
| trace(arr, prev, max_index); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment