FZU 2214 Knapsack problem(背包问题)
| Description | 題目描述 |
| Given a set of n items, each with a weight w[i] and a value v[i], determine a way to choose the items into a knapsack so that the total weight is less than or equal to a given limit B and the total value is as large as possible. Find the maximum total value. (Note that each item can be only chosen once). | 給你n件物品,以及每件物品的質量w[i]和價值v[i]。選擇一種裝包方式使得背包的最終質量小等于上限B并且最終價值盡可能大。找出最大的總價值。(注意,每件物品只能被選擇一次) |
?
| Input | 輸入 |
| The first line contains the integer T indicating to the number of test cases. For each test case, the first line contains the integers n and B. Following n lines provide the information of each item. The i-th line contains the weight w[i] and the value v[i] of the i-th item respectively. 1 <= number of test cases <= 100 1 <= n <= 500 1 <= B, w[i] <= 1000000000 1 <= v[1]+v[2]+...+v[n] <= 5000 All the inputs are integers. | 輸入的首行是一個整數T表示測試樣例的數量。 對于每個測試樣例,第一行包含兩個整數n和B。? 接下來有n行表示每件物品的信息。 第i行分別包含第i件物品的質量w[i]與價值v[i]。 1 <= 測試樣例數量 <= 100 1 <= n <= 500 1 <= B, w[i] <= 1000000000 1 <= v[1]+v[2]+...+v[n] <= 5000 輸入均為整數。 |
?
| Output | 輸出 |
| For each test case, output the maximum value. | 每個測試樣例輸出其最大價值。 |
?
| Sample Input - 輸入樣例 | Sample Output - 輸出樣例 |
| 1 5 15 12 4 2 2 1 1 4 10 1 2 | 15 |
?
【題解】
最大質量為1000000000,數組肯定不夠用。
不過,總價值才5000,我們以價值為軸開辟記錄剩余可載質量的一維數組,后面的做法就與01背包如出一轍。
【代碼 C++】
1 #include<cstdio> 2 #include<cstring> 3 int main(){ 4 int weight[5001], t, i, j, n, B, max_value, w, v; 5 scanf("%d", &t); 6 7 while (t--){ 8 scanf("%d%d", &n, &B); 9 memset(weight, 0, sizeof(weight)); 10 weight[0] = B, max_value = 0; 11 12 for (j = 0; j < n; ++j){ 13 scanf("%d%d", &w, &v); 14 for (i = max_value; i >= 0; --i){ 15 if (weight[i] - w > weight[i + v]) weight[i + v] = weight[i] - w; 16 } 17 for (i = max_value + 1; i <= 5000; ++i) if (weight[i]) max_value = i; 18 } 19 20 printf("%d\n", max_value); 21 } 22 return 0; 23 }?FZU 2214
轉載于:https://www.cnblogs.com/Simon-X/p/5128130.html
總結
以上是生活随笔為你收集整理的FZU 2214 Knapsack problem(背包问题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Gulp 之图片压缩合并
- 下一篇: IOS中UIActionSheet使用方