01背包怎么不重復_帶有重復物品的背包

01背包怎么不重復

Problem statement:

問題陳述:

Weights and values are given for n items along with the maximum capacity allowed W. What is the maximum value we can achieve if we can pick any weights, any number of times for the total allowed capacity of W?

給出了n個項目的權重和值以及允許的最大容量W。 如果可以為W的總允許容量選擇任意權重,任意次數,我們可以實現的最大值是多少?

Input:

輸入:

First line contains two integers N and W denoting the number of items and the total allowed weight.

第一行包含兩個整數NW,分別表示項目數和允許的總重量。

In the next two lines are space separated values of the array denoting values of the items val[n] and their weights weights[n] respectively.

在接下來的兩行中,數組的空格分隔值分別表示項val [n]的值及其權重weight [n]

Output:

輸出:

Output the maximum value which we can achieve if we can pick any weights any number of times for a total weight capacity of W.

如果我們可以選擇任意數量的砝碼來獲得總重量W,則輸出可以達到的最大值。

Constraints:

限制條件:

1 <= N,W <= 100
1 <= weight[i], val[i] <= 100

Example:

例:

Test case: 1
Input:
N=2,W= 3
val[]=1 1
weight[]=2 1 
Output:
Maximum value that can be achieved: 3
Test case: 2
Input:
N=3,W= 4
val[]=2 5 3
weight[]=1 2 1
Output:
Maximum value that can be achieved: 12

Explanation:

說明:

For the first test case,
Will use the second item with weight 1 only. 
We use will 3 such item to have maximum value 3.
Any other combinations will give less value
For the second test case,
Some possible combinations can be
Writing as (value, weight) pair
(2,1), (2,1), (2,1), (2,1)- total weight 4, value 8 
(2,1), (2,1), (5,2) - total weight 4, value 9
...
(3,1),(3,1), (3,1),(3,1)- total weight 4, value 12
The last combination is the most optimal one 
and that's produces the maximum.

Solution Approach:

解決方法:

The difference between this problem and the general knapsack problem is here we can use the same item several times. So the simple recursion about either choosing an item or leaving the item will not work here as using the same item may lead to the most optimized solution.

這個問題和一般背包問題之間的區別在于,我們可以多次使用同一項目。 因此,關于選擇一個項目或離開該項目的簡單遞歸在這里不起作用,因為使用同一項目可能會導致最優化的解決方案。

Hence, the algorithm will be like following,

因此,該算法將如下所示,

  1. Initialize a dp[w+1] to store for each sub-problem up to total capacity W.

    初始化dp [w + 1]為每個子問題存儲直到總容量W。

  2. Reset all the values to zero initially.

    最初將所有值重置為零。

    memset(dp,0,sizeof(dp));

    memset(dp,0,sizeof(dp));

  3. Fill up the DP table with base value dp[0]=0,

    用基本值dp [0] = 0填充DP表,

    for sub-problem weight,i=1 to w
    for a weight,wj in the weight array
    if i>=wj
    dp[i] = std∷max?(dp[i],dp[i-wj]+valj)
    end if
    end for
    end for
    
    
  4. Maximum value that can be achieved is dp[w]

    可以達到的最大值是dp [w]

Let's compute the above for our test case two,

讓我們為測試案例二計算以上內容,

N = 3, W = 4
val[] = 2 5 3
weight[] = 1 2 1

Initially the DP table is,

最初,DP表是

knapsack with duplicate items (1)

To compute dp[1],

要計算dp [1],

weight[0]<=1
So, 
dp[1] = max(dp[1],dp[1-1]+val[0]) = 2
Weight[1]>1. So it can't have any role while computing DP[1]
Weight[2]<=1
So, 
dp[1] = max(dp[1],dp[1-1]+val[2]) = 3

Similar way you can hand compute the DP table to understand how the algo is performing is reaching to the optimal answer.

您可以用類似的方法手工計算DP表,以了解算法的性能如何達到最佳答案。

The final DP table for the above test case would look like,

上述測試用例的最終DP表如下所示:

knapsack with duplicate items (2)

Where 12 is the final case.

最后的情況是12。

C++ Implementation:

C ++實現:

#include <bits/stdc++.h>
using namespace std;
void print(vector<int> a, int n)
{
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
}
int my(vector<int> price, vector<int> weight, int n, int w)
{
int dp[w + 1];
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= w; i++) {
for (int j = 1; j <= n; j++) {
if (i >= weight[j - 1])
dp[i] = std::max(dp[i], dp[i - weight[j - 1]] + price[j - 1]);
}
}
return dp[w];
}
int main()
{
int n, item, w;
cout << "enter number of item and total weights\n";
cin >> n >> w;
cout << "Enter the prices\n";
vector<int> price;
for (int j = 0; j < n; j++) {
scanf("%d", &item);
price.push_back(item);
}
cout << "Enter the weights\n";
vector<int> weight;
for (int j = 0; j < n; j++) {
scanf("%d", &item);
weight.push_back(item);
}
cout << "result is: " << my(price, weight, n, w) << endl;
return 0;
}

Output:

輸出:

enter number of item and total weights
3 4
Enter the prices
2 5 3
Enter the weights
1 2 1
result is: 12

翻譯自: https://www.includehelp.com/icp/knapsack-with-duplicate-items.aspx

01背包怎么不重復

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377509.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377509.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377509.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

jQuery數組處理匯總

有段時間沒寫什么了, 打算把jquery中的比較常用的數組處理方法匯總一下 $.each(array, [callback])遍歷,很常用 ?12345678var arr [javascript, php, java, c, c#, perl, vb, html, css, objective-c];$.each(arr, function(key, val) {// firebug consoleconsole.log(index …

C++ 內存基本構件 placement new

用法以及編譯器解釋 placement new 允許我們將object構建于已經分配的內存上。(所以此時必須有個指針指向已經分配好的內存) 沒有所謂的placement delete &#xff0c;因為placement new根本沒有分配內存. 也有種說法&#xff0c;是將placement new對應的內存釋放掉的操作為pl…

二維數組for遍歷

<?php$conarray(array(1,高某,A公司,北京市,010,abc),array(2,羅某,B公司,天津市,020,bcd),array(3,馮某,C公司,上海市,021,cdf),array(4,書某,D公司,重慶市,022,dfg));echo <table border"1" width"600" align"center">;echo <cap…

Xcode調試相關小結

一.設置NSZombieEnabled 使用NSZombieEnabled功能,當代碼中訪問已經釋放了內存的地方,會給你下面這樣的提示,而不僅僅是EXEC_BAD_ACCESS: 2008-10-03 18:10:39.933 HelloWorld[1026:20b] *** -[GSFont ascender]: message sent to deallocated instance 0x126550 如果要查看上面…

ONGC的完整形式是什么?

ONGC&#xff1a;石油天然氣公司 (ONGC: Oil and Natural Gas Corporation) ONGC is an abbreviation of Oil and Natural Gas Corporation. It is an Indian multinational corporation that is one of the leading producers of crude oil and natural gas in India. Its hea…

C/C++代碼優化方法

目錄優化概述_O0優化_O1優化_O2優化_O3優化volatile關鍵字避免優化優化概述 如果將未經優化的C語言程序直接運行會發現運行效率較低&#xff0c;并且產生的代碼較大&#xff0c;而通過優化可以較好地解決這些問題。 優化的作用是對循環進行化簡&#xff0c;重新組織表達式和聲…

大學生應當趁早謀劃未來(二)--給表弟的建議

背景表弟&#xff0c;大四&#xff0c;湖北某二本院校&#xff0c;計算機相關專業。大學期間&#xff0c;對Java等編程沒有興趣&#xff0c;幾乎沒怎么學習。平時&#xff0c;課程比較多&#xff0c;每天6節左右。課外&#xff0c;自己去掙點生活費,父親生病了。困境最近在找工…

UVa 490 - Rotating Sentences

把輸入的字符順時針旋轉90度。 1 #include<stdio.h>2 #include<string.h>3 4 int main()5 {6 int i, j, max, n, m;7 char s[105][105];8 max0;9 memset(s, \0, sizeof(s)); 10 for (i0; gets(s[i]); i) 11 { 12 nstrlen(s[i]); 1…

node 大寫_大寫Node.js模塊

node 大寫Today, lets see a third party module that helps us in working with upper-case letters without necessarily typing them in upper-case in our source code. 今天&#xff0c;讓我們看一個第三方模塊&#xff0c;它可以幫助我們處理大寫字母&#xff0c;而不必在…

1704:baoge的洗漱難題[黃]

baoge的洗漱難題[黃] Time Limit: 5000 ms Memory Limit: 65536 KB Total Submit: 79 Accepted: 21 Description眾所周知&#xff0c;地大19樓的盥洗室非常小&#xff0c;所以經常會非常擁擠&#xff0c;很多時候去洗漱的時候不得不排很長的隊。有時候baoge會排上半小時…

HDU嵌入式實驗課程大作業分析報告

目錄作業要求設計原理與思路擴展任務說明課程感受友情鏈接工程鏈接作業要求 體能測試記錄儀設計 基于課程發放的實驗板&#xff0c;設計一個帶有計時和數據采集功能的體能測試記錄儀。 基本設計內容 功能1&#xff1a;對應1000米體測場景&#xff0c;使用充電寶供電&#x…

COJ 1030 素數槽

http://acm.csu.edu.cn/OnlineJudge/problem.php?id1030 用線性篩素數果然快多了。 #include<cstdio> #include<cstring> #include<cstdlib> #define MAXN 1300000 bool is_p[MAXN];void calc() {for( int i 1; i < MAXN; i )is_p[i] true;is_p[1] fa…

html注釋引用公共頭部_HTML注釋和引用

html注釋引用公共頭部HTML注釋 (HTML Comments) To insert a comment in an HTML document, the comment tags are used. The comments are used to provide some information that could be useful for anyone who views the code of the webpage. The comments can be insert…

java連接oracle數據庫 -- jdbc連接

a. 倒入oracle的jar包 b. 編寫java文件 package com.sp; import java.sql.*; //使用jdbc連接oracle public class MyOra2 {/*** param args*/public static void main(String[] args) {// TODO Auto-generated method stubtry {Class.forName("oracle.jdbc.dri…

HDB3碼的編碼

編碼規則 1、源碼是1時&#xff0c;暫時不變&#xff1b; 2、連0不超過3個時不變&#xff0c;有4個或以上連0時把每4個0換為取代節&#xff0c;即B00V&#xff1b; 3、確定B是0還是1&#xff1a;第一個B一般取0&#xff0c;若兩個取代節之間1的個數為偶&#xff0c;易推得后者…

地圖加載(安全沙箱問題及解決方案)

基于Flash開發的軟件瀏覽器插件會受到應用沙盒限制&#xff0c;譬如說在本機發布了地圖服務&#xff0c;在flex中使用localhost獲取地圖時一切正常&#xff0c;但改成IP地址后就會報安全沙箱錯誤。 Flash Player對訪問外部資源有比較嚴格的限制&#xff0c;因此如果需要訪問…

批量去除文件空格

import osfilepath r"G:\picture" # 文件目錄名 allfilepath os.listdir(filepath)for file in allfilepath: # 改目錄下的文件名oldpath filepath \\ filenewname file.replace( , ) # 在原先文件名中去除空格&#xff0c;也就是用null替代空格newpath fil…

python 初始化 元組_在Python中重新初始化元組

python 初始化 元組Python | 重新初始化元組 (Python | Reinitializing tuple) In this tutorial, we will learn how can we reinitialize a tuple with a new set of elements/objects? 在本教程中&#xff0c;我們將學習如何使用一組新的元素/對象重新初始化元組&#xff1…

【DSP復習主要知識點】(大概)

目錄第一章1、數字系統對比模擬系統2、馮諾依曼、哈佛架構3、CISC、RISC4、DSP特點5、cpu流水線作用6、DSP芯片優點第二章&#xff1a;DSP芯片結構原理1、ALU&#xff08;算數邏輯運算單元&#xff09;2、累加器A和B3、桶形移位器的功能4、乘法/加法單元5、CPU狀態與控制寄存器…

PHP CURL POST無法獲取響應內容的問題

現象&#xff1a; 使用PHP的CURL相關函數進行POST&#xff0c;當要POST的參數內容長度超過1024時&#xff0c;將無法獲得response的數據。 即&#xff1a; [php] view plaincopyprint?curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS,…