码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank# Knapsack

时间:2015-05-06 01:14:13      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

原题地址

 

背包问题:容量为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 }

 

HackerRank# Knapsack

标签:

原文地址:http://www.cnblogs.com/boring09/p/4480709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!