Knapsack problem (Anurag Verma) v1.0
Knapsack problem (Anurag Verma) v1.0
Experiment 6
Aim
To implement the Knapsack problem using a greedy approach.
Theory
Knapsack Problem
Given the weights and profits of N items, in the form of {profit, weight} put
these items in a knapsack of capacity W to get the maximum total profit in
the knapsack.
Naive Approach:
Try all possible subsets with all different fractions.
Greedy Approach:
The greedy approach to the Knapsack is an algorithm for making decisions
that have to make a locally optimal choice at each stage in the hope that
this will eventually lead to the best overall decision.
Algorithm:
1. Calculate the ratio profit/weight for each item.
2. Sort the items on the basis of this ratio.
3. Take the item with the highest ratio and add them as much as we can
(can be the whole element or a fraction of it).
47
Anurag Verma EN22CS301175
This will always give the maximum profit because, in each step it adds an
element such that this is the maximum possible profit for that much weight
Code
#include <bits/stdc++.h>
using namespace std;
struct Item {
int value, weight;
// Constructor
Item(int item_value, int item_weight)
: value(item_value), weight(item_weight) {
}
};
/*
48
Anurag Verma EN22CS301175
int curWeight = 0;
double finalvalue = 0.0; // Result (value in
Knapsack)
49
Anurag Verma EN22CS301175
return finalvalue;
}
// Driver code
int main() {
int W = 40; // Weight of knapsack
Item arr[] = {{500, 30}, {100, 20}};
Output
Conclusion
The experiment successfully implemented the Fractional Knapsack
Problem using a greedy approach. By selecting items based on their
profit-to-weight ratio, the algorithm efficiently maximizes the total profit. If
a full item cannot fit, a fractional part is included. The results confirm that
the greedy strategy provides an optimal solution for this problem.
50