Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions C++/Knapsack_0-1.cpp
Original file line number Diff line number Diff line change
@@ -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<bits/stdc++.h>
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;
}
38 changes: 38 additions & 0 deletions C++/Longest_Common_Subsequence.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include<bits/stdc++.h>
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 ;
}