Skip to main content

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].

maxresdefault.jpg

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:

  • KitaWe memilikihave sebuaha tasbag (knapsack) denganwith kapasitasa tertentucertain capacity (W).
  • KitaWe memilikihave beberapaseveral barangitems (items)with dengancertain nilaivalues (val) danand beratweights (wt) tertentu..
  • TujuanOur kitagoal adalahis mengisito tasfill tersebutthe denganbag barang-barangwith sehinggaitems nilaiso that the total barangvalue diof dalamitems tasin maksimalthe tanpabag melebihiis kapasitasmaximized tas.without exceeding the bag's capacity.
  • KitaWe menggunakanuse pendekatana dinamis (dynamic programming)programming untukapproach menyelesaikanto masalahsolve inithis denganproblem efisien.efficiently.
  • Pertama-tama,First, kitawe iterasiiterate setiapthrough barang,each danitem, untukand setiapfor barang,each kitaitem, iterasiwe kapasitasiterate tasthe daribag belakangcapacity kefrom depanback to front (misale.g., darifrom beratmaximum maksimumweight keto 0).
  • DenganThis caraway, ini,we nantiwill kitafind akanthe carimaximum maksimalvalue nilaithat yangcan bisabe dimasukkanput keinto dalamthe tasbag tanpawithout melebihiexceeding kapasitasnya.its capacity.
  • KodeThe tersebutcode sudahalready mencakupcovers situasithe membandingkansituation antaraof menggunakancomparing nilaibetween barangusing denganthe item with the highest weight tertinggior atauadding menambahkanan nilaiitem barangwith dengana lower weight lebihwith rendahthe denganremaining kapasitas tas yang lebih kecil.capacity.