背包问题:容量为k,物品的体积和价值相等,求最大价值是多少
代码:
1 #include <cmath> 2 #include <cstdio> 3 #include <vector> 4 #include <iostream> 5 #include <algorithm> 6 #include <cstring> 7 using namespace std; 8 9 #define MAX_N 2048 10 #define MAX_K 2048 11 12 int T; 13 int n, k; 14 int a[MAX_N]; 15 int cnt[MAX_K]; 16 17 int main() { 18 /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 19 cin >> T; 20 while (T--) { 21 int best = 0; 22 cin >> n >> k; 23 for (int i = 0; i < n; i++) 24 cin >> a[i]; 25 memset(cnt, 0, sizeof(cnt)); 26 for (int i = n - 1; i >= 0; i--) 27 for (int j = 0; j <= k; j++) 28 cnt[j] = max(j >= a[i] ? cnt[j - a[i]] + a[i] : 0, cnt[j]); 29 cout << cnt[k] << endl; 30 } 31 return 0; 32 }
时间: 2024-10-26 15:37:17