DAA - Lab Manual - Exp - 5
DAA - Lab Manual - Exp - 5
Experiment No.05
A.1 Aim:
Analyze and implement the solution for Knapsack Problem using Greedy Technique.
Task1:
A thief is robbing a store and can carry a maximal weight of W into his knapsack.
There are n items available in the store and weight of i th item is wi and its profit is pi.
What items should the thief take?
In this context, the items should be selected in such a way that the thief will carry
those items for which he will gain maximum profit. Hence, the objective of the thief
is to maximize the profit.
A thief is robbing a store and has a knapsack that can carry a maximum weight of W
= 20 kg. There are 5 items available in the store, each with a specific weight and
corresponding profit, as shown in the table below:
Weight Profit
Item
(kg) (₹)
1 5 30
2 10 40
3 15 45
4 7 25
5 8 24
Using the Greedy Method, determine which items the thief should take to maximize
the total profit, considering that fractional parts of items can be taken (Fractional
Knapsack).
Task2: Implement the solution for the above Knapsack Problem using Greedy
Technique.
A.2 Prerequisite:
1. Knowledge of Array Handling and
A.3 Outcome:
After successful completion of this experiment students will be able to
1. Understand the concept of divide and conquer paradigm with the help
of Quick sort Algorithm
2. Write complex program based on recursion.
A.4 Theory:
A.4.1.
Fractional Knapsack:
In this case, items can be broken into smaller pieces, hence the thief can select
fractions of items. According to the problem statement,
There are n items in the store
Weight of ith item wi>0
Profit for ith item pi>0 and
Capacity of the Knapsack is W
In this version of Knapsack problem, items can be broken into smaller pieces. So, the
thief may take only a fraction xi of ith item.
0⩽xi⩽1
The ith item contributes the weight xi*wi to the total weight in the knapsack and profit
xi*pi to the total profit.
Subject to constraint,
n
∑ Xi∗Wi ≤W
n =1
It is clear that an optimal solution must fill the knapsack exactly, otherwise we could
add a fraction of one of the remaining items and increase the overall profit.
Thus, an optimal solution can be obtained by
n
∑ Xi∗Wi=W
n =1
In this context, first we need to sort those items according to the value of pi / wi, so
that (pi+1)/( wi+1) ≤ pi /wi . Here, x is an array to store the fraction of items.
PART B
(PART B : TO BE COMPLETED BY STUDENTS)
(Students must submit the soft copy as per following segments within two hours of
the practical.
The soft copy must be uploaded on the Portal.)
Division: - Batch : -
Grade : -