日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

FZU 2214 Knapsack problem(背包问题)

發布時間:2025/3/21 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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(背包问题)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。