TheAlgorithms-C-Plus-Plus/dynamic_programming/0_1_knapsack.cpp

73 lines
1.5 KiB
C++
Raw Normal View History

// 0-1 Knapsack problem - Dynamic programming
2017-04-10 19:18:35 +08:00
//#include <bits/stdc++.h>
2019-08-21 10:10:08 +08:00
#include <iostream>
2016-11-28 00:21:40 +08:00
using namespace std;
2017-04-10 19:18:35 +08:00
// void Print(int res[20][20], int i, int j, int capacity)
2017-04-10 19:18:35 +08:00
//{
// if(i==0 || j==0)
// {
// return;
// }
// if(res[i-1][j]==res[i][j-1])
// {
// if(i<=capacity)
// {
// cout<<i<<" ";
// }
2019-08-21 10:10:08 +08:00
//
2017-04-10 19:18:35 +08:00
// 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);
// }
//}
2019-08-21 10:10:08 +08:00
int Knapsack(int capacity, int n, int weight[], int value[])
{
int res[20][20];
for (int i = 0; i < n + 1; ++i)
{
for (int j = 0; j < capacity + 1; ++j)
{
if (i == 0 || j == 0)
res[i][j] = 0;
else if (weight[i - 1] <= j)
res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]],
res[i - 1][j]);
else
res[i][j] = res[i - 1][j];
}
}
// Print(res, n, capacity, capacity);
// cout<<"\n";
return res[n][capacity];
2016-11-28 00:21:40 +08:00
}
2017-04-10 19:18:35 +08:00
int main()
2016-11-28 00:21:40 +08:00
{
int n;
cout << "Enter number of items: ";
cin >> n;
int weight[n], value[n];
cout << "Enter weights: ";
for (int i = 0; i < n; ++i)
{
cin >> weight[i];
}
cout << "Enter values: ";
for (int i = 0; i < n; ++i)
{
cin >> value[i];
}
int capacity;
cout << "Enter capacity: ";
cin >> capacity;
cout << Knapsack(capacity, n, weight, value);
return 0;
2017-04-10 19:18:35 +08:00
}