0-1背包变形

最小邮票数

http://www.nowcoder.com/questionTerminal/83800ae3292b4256b7349ded5f178dd1

代码和0-1背包非常之像,只是由原来的容量固定,求最大价值,最小邮票数是每个邮票的价值(权重)一样,都为1(枚),在背包大小固定的情况,求最少的邮票数。

// runtime: 4ms
// space: 496K
#include <iostream>
#include <algorithm>
using namespace std;

const int MAX = 100000;

int main() {
    int total, n;
    while (cin>> total >> n) {
        int stamp[n + 1];
        int dp[n + 1][total + 1]; // dp[i][j] stands for min number of
        for (int i = 1; i <= n; ++i) {
            cin >> stamp[i];

        } // end of input

        for (int i = 0; i <= n; ++i) {
            for (int j = 0; j <= total; ++j) {
                dp[i][j] = MAX;
            }
        } // initialize dp
        dp[0][0] = 0; // very important

        for (int i = 1; i <= n; ++i) {
            for (int j = 0; j <= total; ++j) {
                if (j < stamp[i]) { // can not select this stamp
                    dp[i][j] = dp[i - 1][j];
                    continue;
                }
                else { // select this stamp
                    dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - stamp[i]] + 1); // +1 means plus one stamp.
                }
            }
        }

        if (dp[n][total] == MAX) // can not combined into TOTAL
            cout << 0 << endl;
        else
            cout <<dp[n][total] << endl;
    }
    return 0;
}
全部评论
请问那个dp[0][0]初始化为0如何理解?
点赞 回复 分享
发布于 2020-04-17 17:20

相关推荐

兄弟们你们进大厂靠的是什么项目啊
DOTPHTP:课设改。其实项目什么的如果不是实习里面的生产项目的话,建议✍️那种自己想要做的。突出个人自驱力,而不是为了找工作不得不随波逐流这种
点赞 评论 收藏
分享
每晚夜里独自颤抖:这个在牛客不是老熟人了吗
点赞 评论 收藏
分享
废物一个0offer:认真的吗二本本科找人工智能岗位
点赞 评论 收藏
分享
風に薫る:前阵子把一个面试时老托腮抖腿的挂了 太松弛真不行
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务