knaspsack dynamic

This commit is contained in:
AnupKumarPanwar
2017-04-10 16:48:35 +05:30
parent 496b63642d
commit 50dd987810
2 changed files with 33 additions and 4 deletions

View File

@@ -1,8 +1,35 @@
//0-1 Knapsack problem - Dynamic programming
#include <bits/stdc++.h>
//#include <bits/stdc++.h>
#include<iostream>
using namespace std;
//void Print(int res[20][20], int i, int j, int capacity)
//{
// if(i==0 || j==0)
// {
// return;
// }
// if(res[i-1][j]==res[i][j-1])
// {
// if(i<=capacity)
// {
// cout<<i<<" ";
// }
//
// Print(res, i-1, j-1, capacity-i);
// }
// else if(res[i-1][j]>res[i][j-1])
// {
// Print(res, i-1,j, capacity);
// }
// else if(res[i][j-1]>res[i-1][j])
// {
// Print(res, i,j-1, capacity);
// }
//}
int Knapsack(int capacity,int n,int weight[],int value[]){
int res[n+1][capacity+1];
int res[20][20];
for (int i = 0; i < n+1; ++i)
{
for (int j = 0; j < capacity+1; ++j)
@@ -15,9 +42,11 @@ int Knapsack(int capacity,int n,int weight[],int value[]){
res[i][j] = res[i-1][j];
}
}
// Print(res, n, capacity, capacity);
// cout<<"\n";
return res[n][capacity];
}
int main(int argc, char const *argv[])
int main()
{
int n;
cout<<"Enter number of items: ";
@@ -38,4 +67,4 @@ int main(int argc, char const *argv[])
cin>>capacity;
cout<<Knapsack(capacity,n,weight,value);
return 0;
}
}

Binary file not shown.