【题目来源】
https://www.acwing.com/problem/content/description/2/
【题目描述】
有 N 件物品和一个容量是 V 的背包。每件物品只能使用一次。
第 i 件物品的体积是 vi,价值是 wi。
求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大。
输出最大价值。
【输入格式】
第一行两个整数,N,V,用空格隔开,分别表示物品数量和背包容积。
接下来有 N 行,每行两个整数 vi,wi,用空格隔开,分别表示第 i 件物品的体积和价值。
【输出格式】
输出一个整数,表示最大价值。
【数据范围】
0<N,V≤1000
0<vi,wi≤1000
【算法代码一】
#include <bits/stdc++.h>
using namespace std;
const int maxn=1005;
int vol[maxn]; //volume
int val[maxn]; //value
int c[maxn][maxn]; //c[i][j], the maximum value of the previous i items under j volume
int f[maxn];
int main() {
int n,V;
cin>>n>>V;
for(int i=1; i<=n; i++)
cin>>vol[i]>>val[i];
for(int i=1; i<=n; i++)
for(int j=1; j<=V; j++) {
//If the current backpack can't hold the i-th item, the value is equal to the previous i-1 item
if(j<vol[i]) c[i][j]=c[i-1][j];
//If yes, the decision is made whether to select item i
else c[i][j]=max(c[i-1][j],c[i-1][j-vol[i]]+val[i]);
}
cout<<c[n][V]<<endl;
return 0;
}
/*
in:
5 4
1 20
4 30
1 15
3 20
1 10
out:
45
============
in:
4 5
1 2
2 4
3 4
4 5
out:
8
*/
【算法代码二(一维数组优化)】
#include<bits/stdc++.h>
using namespace std;
const int maxn=1005;
int c[maxn];
int main() {
int n,V;
cin>>n>>V;
for(int i=1;i<=n;i++){
int vol,val;
cin>>vol>>val;
for(int j=V;j>=vol;j--)
c[j]=max(c[j],c[j-vol]+val);
}
cout<<c[V]<<endl;
return 0;
}
/*
in:
4 5
1 2
2 4
3 4
4 5
out:
8
*/
【参考文献】
https://www.acwing.com/solution/content/1374/