1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include <stdio.h> #include <iostream> #include <vector> #include <string.h> using namespace std; void package(int *weight,int *size,int n,int c); void getResult(int n,int c,int *res,int *size,int *weight); int f[10][100];
int main(){ vector<int> vweight; vector<int> vsize; int number; vweight.push_back(0); vsize.push_back(0); cout << "请输入每个物品的重量:"; while (1){ cin >> number; vweight.push_back(number); if (cin.get() == '\n') break; } int *weight = new int[vweight.size()]; if (!vweight.empty()){ memcpy(weight, &vweight[0], vweight.size()*sizeof(int)); } cout << "请输入每个物品的价值:"; while (1) { cin >> number; vsize.push_back(number); if (cin.get() == '\n') break; } int *size = new int[vsize.size()]; if (!vsize.empty()){ memcpy(size, &vsize[0], vsize.size()*sizeof(int)); } if(vweight.size()!=vsize.size()){ cout << "数据输入错误,请重新开始"; exit(0); } cout << "请输入背包的总容量:"; int c; cin >> c; int n = vweight.size()-1; int res[n]; for(int a=0;a<n;a++){ res[a]=0; }
int i,j; package(weight,size,n,c); for(i=0;i<=n;i++){ for(j=0;j<=c;j++) printf("%2d ",f[i][j]); cout << endl; } getResult(n,c,res,size,weight); cout << "放入背包最大价值: " << f[n][c] << endl; cout << "放入背包的物品为: "; for(i=1;i<=n;i++) if(res[i] == 1) cout << i << " "; }
void package(int *weight,int *size,int n,int c){ int i,j; for(i=1;i<=n;i++) f[i][0] = 0; for(j=1;j<=c;j++) f[0][j] = 0; for(i=1;i<=n;i++){ for(j=1;j<=c;j++){ if(weight[i] <= j && f[i-1][j-weight[i]] + size[i] > f[i-1][j]){ f[i][j] = f[i-1][j-weight[i]] + size[i]; }else f[i][j] = f[i-1][j]; } } }
void getResult(int n,int c,int *res,int *size,int *weight){
int i,j; j = c; for(i=n;i>=1;i--){ if(f[i][j] != f[i-1][j]){ res[i] = 1; j = j - weight[i]; } } }
|