chore(CPlusPlus): add longest common subsequence and topological sort (#388)

Co-authored-by: Ujjwal <75884061+UG-SEP@users.noreply.github.com>
pull/390/head
Ellika Mishra 2021-07-16 00:55:43 +05:30 committed by GitHub
parent 8703a9e533
commit a2c225f53e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,88 @@
/*
Printing longest common subseqeunce from 2 subsequences using dp bottom-up approach
*/
#include<bits/stdc++.h>
using namespace std;
void longestCommonSubsequence(vector < int > a, vector < int > b) {
int n = a.size();
int m = b.size();
int i, j;
vector < vector < int >> dp(n + 1, vector < int > (m + 1, 0)); //creating lookup table to keep track of subsequnces
vector < int > result; //result vector
for (i = 1; i <= n; i++) {
for (j = 1; j <= m; j++) //iterating through all subsequences, if common then increment value of dp[i][j] else consider max from previous
{
if (a[i - 1] == b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
i = n, j = m;
while (i > 0 && j > 0) { //traversing dp vector and finding the same elements in both to print result
if (a[i - 1] == b[j - 1]) {
result.push_back(a[i - 1]);
i--;
j--;
} else if (dp[i][j - 1] > dp[i - 1][j]) {
j--;
} else
i--;
}
cout << "Length of lcs " << result.size() << '\n';
reverse(result.begin(), result.end()); //reversing to get correct order
cout << "\nLongest common subsequence ";
for (auto it: result) {
cout << it;
}
cout << "\n";
}
int main() {
int n, m;
cout << "\nEnter no of elements in first sequence"; //Input and output
cin >> n;
cout << "\nEnter no of elements in second sequence";
cin >> m;
vector < int > a(n);
vector < int > b(m);
cout << "\nEnter elements in first sequence\n";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
cout << "\nEnter elements in second sequence\n";
for (int i = 0; i < m; i++) {
cin >> b[i];
}
longestCommonSubsequence(a, b);
return 0;
}
/*
Time and space complexity for subsequence-O(m*n)
SAMPLE INPUT-
Enter no of elements in first sequence5
Enter no of elements in second sequence3
Enter elements in first sequence
1 2 3 4 5
Enter elements in second sequence
1 3 4
Length of lcs 3
Longest common subsequence 134
*/

View File

@ -12,6 +12,11 @@
8. [Sorted-Rotated Search Array](Arrays/search-sorted-rotated.cpp)
9. [Fractional Knapsack](Arrays/fractional-knapsack.cpp)
## Dynamic-Programming
1. [Longest Common Subsequence](Dynamic-Programming/longest-common-subsequence.cpp)
## Graphs
1. [Bellman Ford Algorithm](Graphs/bellmam-ford.cpp)