Code & Examples 2
Knapsack Problem
Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. The constraint here is we can either put an item completely into the bag or cannot put it at all [It is not possible to put a part of an item into the bag].
Solution:
#include <bits/stdc++.h>
using namespace std;
// Function untukto mencarifind the maximum profit maksimalin dalam suatua knapsack
int knapsack(int W, vector<int> &val, vector<int> &wt) {
// InisialisasiInitialize dp array dpwith denganinitial nilai awalvalue 0
vector<int> dp(W + 1, 0);
// MengambilIterate setiapthrough each item, mulaistarting darifrom the 1st item ke-1to hinggathe nth item ke-n
for (int i = 1; i <= wt.size(); i++) {
// MulaiStart darifrom belakang,the sehinggaback, kitaso jugawe memilikialso have data darifrom
// perhitunganprevious sebelumnyacalculations dariof i-1 itemitems danand menghindariavoid duplikasiduplication
for (int j = W; j >= wt[i - 1]; j--) {
dp[j] = max(dp[j], dp[j - wt[i - 1]] + val[i - 1]);
}
}
return dp[W];
}
int main() {
vector<int> val = {1, 2, 3};
vector<int> wt = {4, 5, 1};
int W = 4;
cout << knapsack(W, val, wt) << endl;
return 0;
}
Penjelasan Program:Explanation:
KodeThe dicode atasabove sudahis bersifatalready optimized karenaas menghematit penggunaansaves memorimemory danusage waktuand eksekusi.execution Analogitime. untukThe analogy for this program iniis adalahas sebagai berikut:follows:
KitaWememilikihavesebuahatasbag (knapsack)denganwithkapasitasatertentucertain capacity (W).KitaWememilikihavebeberapaseveralbarangitems(items)withdengancertainnilaivalues (val)danandberatweights (wt)tertentu..TujuanOurkitagoaladalahismengisitotasfilltersebutthedenganbagbarang-barangwithsehinggaitemsnilaiso that the totalbarangvaluediofdalamitemstasinmaksimalthetanpabagmelebihiiskapasitasmaximizedtas.without exceeding the bag's capacity.KitaWemenggunakanusependekatanadinamis (dynamicprogramming)programminguntukapproachmenyelesaikantomasalahsolveinithisdenganproblemefisien.efficiently.Pertama-tama,First,kitaweiterasiiteratesetiapthroughbarang,eachdanitem,untukandsetiapforbarang,eachkitaitem,iterasiwekapasitasiteratetasthedaribagbelakangcapacitykefromdepanback to front (misale.g.,darifromberatmaximummaksimumweightketo 0).DenganThiscaraway,ini,wenantiwillkitafindakanthecarimaximummaksimalvaluenilaithatyangcanbisabedimasukkanputkeintodalamthetasbagtanpawithoutmelebihiexceedingkapasitasnya.its capacity.KodeThetersebutcodesudahalreadymencakupcoverssituasithemembandingkansituationantaraofmenggunakancomparingnilaibetweenbarangusingdenganthe item with the highest weighttertinggioratauaddingmenambahkanannilaiitembarangwithdengana lower weightlebihwithrendahthedenganremainingkapasitas tas yang lebih kecil.capacity.