Reference
代码随想录 (programmercarl.com)
正文
需要注意写代码的时候,在写递推公式的时候,注意要背包装得下再进行递推。
总是忘记这一点
1
| for(int j = weights[i]; j <= bagSize; j++) {
|
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| #include<iostream> #include<vector> using namespace std; int backQuiz(int bagSize,vector<int>& weights,vector<int>& values){ vector<int> dp(bagSize + 1,0); for(int i = 0; i < weights.size(); i++) { for(int j = weights[i]; j <= bagSize; j++) { dp[j] = max(dp[j],dp[j - weights[i]] + values[i]); } } return dp[bagSize]; } int main() { vector<int> weights; vector<int> values; int N,V; cin >> N >> V; for (int i = 0; i < N; i++) { int tempValue,tempWeight; cin >> tempWeight >> tempValue; weights.push_back(tempWeight); values.push_back(tempValue); } int res = backQuiz(V,weights,values); cout << res << endl; return 0; }
|