http://noi.openjudge.cn/ch0206/8785/
有一个箱子容量为V(正整数,0<=v<=20000),同时有n个物品(0< n<n<=30),每个物品有一个体积(正整数)。< n<="" p="">
要求n个物品中,任取若干个装入箱内,使箱子的剩余空间为最小。
24 6 8 3 12 7 9 7
0
思路:
0-1背包题。
1 #include<iostream> 2 #include<string> 3 #include<cstring> 4 #include<algorithm> 5 using namespace std; 6 7 int n, v; 8 int a[35]; 9 int d[20005]; 10 11 int main() 12 { 13 //freopen("D:\\txt.txt", "r", stdin); 14 while (cin >> v) 15 { 16 memset(d, 0, sizeof(d)); 17 cin >> n; 18 for (int i = 1; i <= n; i++) 19 cin >> a[i]; 20 for (int i = 1; i <= n; i++) 21 { 22 for (int j = v; j >= a[i]; j--) 23 d[j] = max(d[j], d[j - a[i]] + a[i]); 24 } 25 cout << v - d[v] << endl; 26 } 27 return 0; 28 }
原文:http://www.cnblogs.com/zyb993963526/p/6384524.html