【题目来源】
https://www.luogu.com.cn/problem/P1049
https://www.acwing.com/problem/content/1026/
【题目描述】
有一个箱子容量为 V,同时有 n 个物品,每个物品有一个体积(正整数)。
要求 n 个物品中,任取若干个装入箱内,使箱子的剩余空间为最小。
【输入格式】
第一行是一个整数 V,表示箱子容量。
第二行是一个整数 n,表示物品数。
接下来 n 行,每行一个正整数(不超过10000),分别表示这 n 个物品的各自体积。
【输出格式】
一个整数,表示箱子剩余空间。
【数据范围】
0<V≤20000,0<n≤30
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int maxv=20005,maxn=35;
int vol[maxn];
int c[maxn][maxv];
//c[i][j]: The previous i items which total volume does not exceed j
int main() {
int V,n;
cin>>V>>n;
for(int i=1; i<=n; i++) cin>>vol[i];
for(int i=1; i<=n; i++) {
for(int j=1; j<=V; j++) {
c[i][j]=c[i-1][j]; //Don't select current item
if(j>=vol[i]) c[i][j]=max(c[i][j],c[i-1][j-vol[i]]+vol[i]);
//Select the current item and the volume must be sufficient
}
}
cout<<V-c[n][V]<<endl; //Free space
return 0;
}
/*
in:
24
6
8
3
12
7
9
7
out:
0
*/