#include <iostream>
#include <vector>
using namespace std;
void dynamic_0_1(int* v, int* w, int weight, vector< vector<int> >& c, vector<int>& s){
for(int i=1;i<s.size();i++){
for(int j=1;j<=weight;j++)
cout<<c[i][j]<<" ";
cout<<"\n";
}
for(int i=1; i<s.size(); i++){
cout<<s[i]<<" ";
}
cout<<endl;
for(int i=1; i<s.size(); i++){
for(int cw=1; cw<=weight; cw++){
if(w[i]<=cw){
//c[i][cw] = c[i-1][cw-w[i]] + v[i] > c[i-1][cw] ? c[i-1][cw-w[i]] + v[i] : c[i-1][w];
if(c[i-1][cw-w[i]] + v[i] > c[i-1][cw]){
c[i][cw] = c[i-1][cw-w[i]] + v[i] ;
s[i]=1;
if(c[i-1][cw-w[i]] == 0)
s[i-1]=0;
}
else{
c[i][cw] = c[i-1][cw];
s[i]=0;
}
}
else{
c[i][cw] = c[i-1][cw];
s[i]=0;
}
}
}
}
int main()
{
int n = 3;//物品数量
int v[3+1] = { 0, 60, 100, 120 };
int w[3+1] = { 0, 10, 20, 30 };
int weight = 50;
vector< vector<int> > c(n+1,vector<int>(weight+1,0));
vector<int> s(n+1,0);
dynamic_0_1(&v[0],&w[0],weight,c,s);
for(int i=1;i<s.size();i++){
for(int j=1;j<=weight;j++)
cout<<c[i][j]<<" ";
cout<<"\n";
}
for(int i=1; i<s.size(); i++){
cout<<s[i]<<" ";
}
return 0;
}
网友评论