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

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

FZU 2214 Knapsack problem(背包问题)

發(fā)布時(shí)間:2025/3/21 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 FZU 2214 Knapsack problem(背包问题) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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件物品,以及每件物品的質(zhì)量w[i]和價(jià)值v[i]。選擇一種裝包方式使得背包的最終質(zhì)量小等于上限B并且最終價(jià)值盡可能大。找出最大的總價(jià)值。(注意,每件物品只能被選擇一次)

?

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.

輸入的首行是一個(gè)整數(shù)T表示測(cè)試樣例的數(shù)量。

對(duì)于每個(gè)測(cè)試樣例,第一行包含兩個(gè)整數(shù)n和B。?

接下來(lái)有n行表示每件物品的信息。

第i行分別包含第i件物品的質(zhì)量w[i]與價(jià)值v[i]。

1 <= 測(cè)試樣例數(shù)量 <= 100

1 <= n <= 500

1 <= B, w[i] <= 1000000000

1 <= v[1]+v[2]+...+v[n] <= 5000

輸入均為整數(shù)。

?

Output

輸出

For each test case, output the maximum value.

每個(gè)測(cè)試樣例輸出其最大價(jià)值。

?

Sample Input - 輸入樣例

Sample Output - 輸出樣例

1

5 15

12 4

2 2

1 1

4 10

1 2

15

?

【題解】

最大質(zhì)量為1000000000,數(shù)組肯定不夠用。

不過(guò),總價(jià)值才5000,我們以價(jià)值為軸開(kāi)辟記錄剩余可載質(zhì)量的一維數(shù)組,后面的做法就與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

轉(zhuǎn)載于:https://www.cnblogs.com/Simon-X/p/5128130.html

總結(jié)

以上是生活随笔為你收集整理的FZU 2214 Knapsack problem(背包问题)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。