Sicily 1782. Knapsack

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值