#include <bits/stdc++.h>
using namespace std;
int getMax(vector<vector<int>> bags,int X)
{//bags:包裹 X:总容量
int nums = bags.size();//包裹数量
int prices[nums+1][X+1];//这里多一行多一列的意思是放入0个物品和容量为0时
for (int i = 0; i <= nums; ++i) {//初始化第一列(包裹总容量为0时)为0
prices[i][0]=0;
}
for (int j = 0; j <= X; ++j) {//初始化第一行(放0个物品时)为0
prices[0][j]=0;
}
for (int k = 1; k <= nums; ++k) {//逐个包裹
int price = bags[k-1][0];
int cost = bags[k-1][1];
for (int i = 1; i <= X; ++i) {
if (cost>i)
{//如果当前包裹的占空大于i,就不放
prices[k][i] = prices[k-1][i];
} else
prices[k][i] = max(prices[k-1][i],prices[k-1][i-cost]+price);//状态转移公式
}
}
return prices[nums][X];
}
int getMax_MinSpace(vector<vector<int>> bags,int X) {//优化空间复杂度,bags:包裹 X:总容量
int nums = bags.size();//包裹数量
int prices[X + 1];
for (int i = 0; i <= X+1; ++i) {
prices[i]=0;
}
for (int j = 0; j < nums; ++j) {
int price = bags[j][0];
int cost = bags[j][1];
for (int i = X; i >= 1; --i) {
if (cost<=i)
{
prices[i]=max(prices[i],prices[i-cost]+price);
}
}
}
return prices[X];
}
int main()
{
int N,X;
cin>>X>>N;//N:包裹个数;X:总空间
vector<vector<int>> bags;
vector<int> bag;
for (int j = 0; j < N; ++j) {
bag.clear();
int A,B;//价值,占空间
cin>>A>>B;
bag.push_back(B);
bag.push_back(A);
bags.push_back(bag);
}
int max = getMax_MinSpace(bags,X);
cout<<max;
return 0;
}
01背包问题
最新推荐文章于 2023-04-21 16:58:11 发布