刷一下简单的背包问题
以下为代码:
1 //1342. 开心的金明 2 #include <iostream> 3 using namespace std; 4 5 #define MAX(a,b) a>b?a:b 6 7 int backpack(int w[], int v[], int n, int c) 8 { 9 //w表示重要度 10 //v表示价格 11 //c表示价格总量 12 int max[n+1][c+1]; 13 for (int j = 0; j <= c; j++) 14 { 15 if (j<v[1]) max[1][j] = 0; 16 else max[1][j] = w[1]*v[1]; 17 } 18 for (int i = 2; i <= n; i++) 19 { 20 for (int j = 0; j <= c; j++) 21 { 22 if (j < v[i]) max[i][j] = max[i-1][j]; 23 else max[i][j] = MAX(max[i-1][j], (max[i-1][j-v[i]]+v[i]*w[i])); 24 } 25 } 26 return max[n][c]; 27 } 28 29 int main() 30 { 31 int c, n; 32 while (cin>>c>>n) 33 { 34 int w[n+1], v[n+1]; 35 for (int i = 1; i <= n; i++) cin>>v[i]>>w[i]; 36 cout<<backpack(w,v,n,c)<<endl; 37 } 38 return 0; 39 }
时间: 2024-10-05 04:58:25