TheAlgorithms-C-Plus-Plus/dynamic_programming/0-1 Knapsack.cpp

72 lines
1.3 KiB
C++
Raw Normal View History

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