题解 | #【模板】01背包#

【模板】01背包

https://www.nowcoder.com/practice/fd55637d3f24484e96dad9e992d3f62e

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int main(){
    int i,j,n,c;
    int ans1,ans2 = 0;
    cin >> n >> c;
    int w[1001],v[1001];
    for(i = 1; i <= n; i++) cin >> w[i] >> v[i];
    int V[1001][1001];
    int Vi[1001][1001];
    for (i = 0; i <= n ; ++i) {
        V[i][0] = 0;
    }
    for (j = 0; j <= c; ++j) {
        V[0][j] = 0;
    }

    for (i = 1; i <= n; ++i) {
        for (j = 1; j <= c; ++j) {
            if (j < w[i]){
                V[i][j] = V[i - 1][j];
            } else{
                V[i][j] = max(V[i - 1][j],V[i - 1][j - w[i]] + v[i]);
            }
        }
    }

    cout << V[n][c] << endl;
    for (i = 0; i <= n; i++) {
        for(j = 0;j<= c;j++){
            Vi[i][j] = -9999;
        }
    }
    Vi[0][0]=0;
    for (i = 1; i <= n; i++) {
        for (j = 0; j <= c; j++) {
            if (w[i] > j) {
                Vi[i][j] = Vi[i - 1][j];
            } else {
                Vi[i][j] = max(Vi[i - 1][j],Vi[i - 1][j - w[i]] + v[i]);
            }
        }
    }
    if(Vi[n][c]<0){
        Vi[n][c]=0;
    }
    cout<<Vi[n][c];


}

全部评论

相关推荐

11-18 15:57
门头沟学院 Java
最终归宿是测开:这个重邮的大佬在重邮很有名的,他就喜欢打92的脸,越有人质疑他,他越觉得爽😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务