backpack 3 (lintcode 440)

图片.png

图片.png
class Solution {
public:

    int backPackIII( vector &A, vector &V,int m) {
        int ss = A.size();
        if (ss == 0)
            return 0;
        vector> dp(ss + 1, vector(m + 1, 0));
        for (int j = 1; j <= m; j++) {
            dp[0][j] = -1;
        }

        for (int i = 1; i <= ss; i++) {
            for (int j = 0; j <= m; j++) {
                dp[i][j] = dp[i - 1][j];
                if (j - A[i - 1] >= 0 && dp[i][j - A[i - 1]] != -1) {
                    dp[i][j] = max(dp[i][j], dp[i][j - A[i - 1]] + V[i - 1]);
                }
            }
        }

        int ans = 0;
        for (int i = m; i >= 0; i--) {
            ans = max(ans, dp[ss][i]);
        }
        return ans;
    }
};

你可能感兴趣的:(backpack 3 (lintcode 440))