Sicily 1782. Knapsack

来源:互联网 发布:免费配货软件下载 编辑:程序博客网 时间:2024/05/18 01:11

Time Limit: 1 secs, Memory Limit: 63.9990234375 MB

Description

John wants to carry several items with a knapsack. Each item has integral size and can not be divided into smaller parts. The knapsack also has an integral capacity. Given n items, what’s the maximal size of items can be carried without exceeding the knapsack‘s capacity?

Input

This problem contains several test cases. The first line of the input is an integer T, which means there’re T test cases follow. (0 < T ≤ 20)
Each test case contains two lines. The first line contains two integers n, m, which means that there’re n items totally, and the capacity of the knapsack is m. The second line contains n positive integers, the sizes (smaller than m) of different items. (0 < n ≤ 1000, 0 < m ≤ 10000)

Output

For each test case, output one line containing the answer desired.

Sample Input

2
3 10
2 4 7
5 100
2 12 81 63 23
Sample Output

9
100


[]~( ̄▽ ̄)~* 动态规划、01背包?我好方~~~
Just do it!

#include <algorithm>#include <iostream>#include <cstring>using namespace std;int main(){    int T, n, m, item[1010], capacity[10010];    cin >> T;    while (T--)    {        cin >> n >> m;        for (int i = 1; i <= n; i++)            cin >> item[i];        memset(capacity, 0, sizeof(capacity));        //// capacity[j] 表示容量j的背包的物品收纳量        //// capacity[j - item[i]] + item[i] 表示当前物品item[i]放入容量j的背包后背包j的总收纳量        for (int i = 1; i <= n; i++)            for (int j = m; j >= item[i]; j--)                capacity[j] = max(capacity[j], capacity[j - item[i]] + item[i]);        cout << capacity[m] << endl;    }    return 0;}

参考了大神的想法:Ederick的专栏
这里表示感谢!

0 0
原创粉丝点击