题解 | #【模板】完全背包#

【模板】完全背包

http://www.nowcoder.com/practice/237ae40ea1e84d8980c1d5666d1c53bc


#include <vector>
#include <iostream>
#include <limits.h>

using namespace std;

int compute(int n, int V, vector<vector<int>>& vw, vector<int>& dp)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = vw[i][0]; j <= V; j++)
        {
            dp[j] = max(dp[j], dp[j-vw[i][0]] + vw[i][1]);
        }
    }
    
    return dp[V];
}

int fullbag(int n, int V, vector<vector<int>>& vw, bool p1) {
    
    int ret = 0;
    if (p1){
        vector<int> dp(V+1, 0);
        ret = compute(n, V, vw, dp);
    }
    else
    {
        vector<int> dp(V+1, INT_MIN);
        dp[0] = 0;
        ret = compute(n, V, vw, dp);
        if (ret < 0) ret = 0;
    }

    return ret;
}


int main()
{
    int n, V;
    cin >> n >> V;
    vector<vector<int>> vw;
    
    for (int i = 0; i < n; i++)
    {
        int v, w;
        vector<int> tmp;
        cin >> v >> w;
        tmp.push_back(v);
        tmp.push_back(w);
        vw.push_back(tmp);
    }
    

    cout << fullbag(n, V, vw, true) << endl;
    cout << fullbag(n, V, vw, false) << endl;
    
    return 0;
}

全部评论

相关推荐

Java抽象带篮子:难蚌,点进图片上面就是我的大头😆
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务