#include <iostream>
using namespace std;
void Knapsack(int *v, int *w, int c, int n, int **m);
int main()
{
//0-1 bag problem, using dynamic programming
int c;//weight constrain of the bag
int *v;//value of goods
int n;//kinds of goods
int **m;//m(i,j) means optimal value of i~n goods under weight
constrain j
int i, j;
cout<<"Please input weight
constrain of the bag:";
cin>>c;
cout<<"Please input number of
kinds of goods:";
cin>>n;
if(n <= 0 || c <= 0)
{
cout<<"invalid
arguments"<<endl;
return 0;
}
cout<<"Please input
"<<n<<"
weight of goods:"<<endl;
w = new int[n + 1];
w[0] = 0;
for(i = 1; i <= n; i++)
{
cin>>w[i];
}
cout<<"Please input
"<<n<<"
value of goods:"<<endl;
v = new int[n + 1];
v[0] = 0;
for(i = 1; i <= n; i++)
{
cin>>v[i];
}
m = new int *[n + 1];
for(i = 0; i <= n; i++)
{
m[i] = new int[n + 1];
}
for(i = 0; i <= n; i++)
{
for(j = 0; j <= n; j++)
{
m[i][j] = 0;
}
}
Knapsack(v, w, c, n, m);
cout<<"The optimal value is:
"<<m[1][c]<<endl;
delete m;
delete w;
delete v;
return 0;
}
void Knapsack(int *v, int *w, int c, int n, int **m)
{
int i, j;
int jMax = min(w[n] - 1, c);
for(j = 0; j <= jMax; j++)
{
m[n][j] = 0;
}
for(j = w[n]; j <= c; j++)
{
m[n][j] = v[n];
}
for(i = n - 1; i > 1; i--)
{
jMax = min(w[i] - 1, c);
for(j = 0; j < jMax; j++)
{
m[i][j] = m[i + 1][j];
}
for(j = w[i]; j <= c; j++)
{
m[i][j] = max(m[i + 1][j - w[i]] + v[i], m[i + 1][j]);
}
}
m[1][c] = m[2][c];
if(c >= w[1])
{
m[1][c] = max(m[1][c], m[2][c - w[1]] + v[1]);
}
}
Makefile:
bag1:bag1.o
g++ -o bag1 bag1.o
bag1.o:bag1.cpp
g++ -c bag1.cpp
运行结果:
Please input weight constrain of the bag:10
Please input number of kinds of goods:5
Please input 5 weight of goods:
2
2
6
5
4
Please input 5 value of goods:
6
3
5
4
6
The optimal value is: 15