diff --git a/C++/Knapsack_0-1.cpp b/C++/Knapsack_0-1.cpp new file mode 100644 index 0000000..42374a5 --- /dev/null +++ b/C++/Knapsack_0-1.cpp @@ -0,0 +1,52 @@ +// Problem Statement +/* +Given weights and values of n items, put these items in a knapsack of capacity W to +get the maximum total value in the knapsack. In other words, given two integer arrays +val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items +respectively. Also given an integer W which represents knapsack capacity, +find out the maximum value subset of val[] such that sum of the weights +of this subset is smaller than or equal to W. You cannot break an item, +either pick the complete item or don’t pick it (0-1 property). + +*/ + +// Algorithm : + +// A Dynamic Programming based +// solution for 0-1 Knapsack problem +#include +using namespace std ; + +// Returns the maximum value that +// can be put in a knapsack of capacity W +int knapSack(int W, int wt[], int val[], int n) +{ + int i, w; + int K[n + 1][W + 1]; + + // Build table K[][] in bottom up manner + for (i = 0; i <= n; i++) { + for (w = 0; w <= W; w++) { + if (i == 0 || w == 0) + K[i][w] = 0; + else if (wt[i - 1] <= w) + K[i][w] = max( + val[i - 1] + K[i - 1][w - wt[i - 1]], + K[i - 1][w]); + else + K[i][w] = K[i - 1][w]; + } + } + + return K[n][W]; +} + +int main() +{ + int val[] = { 60, 100, 120 }; + int wt[] = { 10, 20, 30 }; + int W = 50; + int n = sizeof(val) / sizeof(val[0]); + out<< knapSack(W, wt, val, n)) <<'\n'; + return 0; +} diff --git a/C++/Longest_Common_Subsequence.cpp b/C++/Longest_Common_Subsequence.cpp new file mode 100644 index 0000000..5f170e8 --- /dev/null +++ b/C++/Longest_Common_Subsequence.cpp @@ -0,0 +1,38 @@ +#include +using namespace std ; + +int LCS(string a,string b){ + int m = a.length() ; + int n = b.length() ; + + int lcs[m + 1][n + 1]; + + for (int i = 0; i <= m; i++) + { + for (int j = 0; j <= n; j++) + { + if (i == 0 || j == 0) + lcs[i][j] = 0; + + else if (X[i - 1] == Y[j - 1]) + lcs[i][j] = lcs[i - 1][j - 1] + 1; + + else + lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]); + } + } + + /* lcs[m][n] contains length of LCS + for X[0..n-1] and Y[0..m-1] */ + return lcs[m][n]; +} + +int main(){ + string str1,str2 ; + cout << "Take two strings to find their LCS\n"; + cin >> str1 >> str2 ; + cout << "Length of LCS is " + << LCS( str1 , str2 ); + + return 0 ; +} \ No newline at end of file