Loading

AcWing 2.01背包问题

题目链接

https://www.acwing.com/problem/content/2/

题目思路

梦开始的地方,01背包的每个物品只可以选一次
DP思想:“最后”
每次考虑的是最后是否为最优解,从最后一步的最优解向前推,推出每一步的最优解。
01背包就是判断每步是拿当前物品和不拿当前物品的价值进行比较,选择最优解
image

题目代码

#include <iostream>
#include <algorithm>

using namespace std; 
const int N = 1010;
int f[N];
int n, t;

int main()
{
    cin >> n >> t;
    for(int i = 0; i < n; i ++ )
    {
        int v, w;
        cin >> v >> w;
        for(int j = t; j >= v; j -- )
            f[j] = max(f[j], f[j - v] + w);
    }
    cout << f[t] << endl;
    return 0;
}
posted @ 2022-03-31 19:46  vacilie  阅读(29)  评论(0)    收藏  举报