0% found this document useful (0 votes)
8 views9 pages

Cse232 L4

This lab report presents solutions to various algorithmic problems using greedy algorithms, including the Fractional Knapsack Problem, Activity Selection Problem, and balloon bursting problem. Each section includes code implementations and explanations of the algorithms' logic and steps. The report is submitted by Shah Jamil Ahmed to the Department of Computer Science Engineering at BUBT.

Uploaded by

donjamil9383
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views9 pages

Cse232 L4

This lab report presents solutions to various algorithmic problems using greedy algorithms, including the Fractional Knapsack Problem, Activity Selection Problem, and balloon bursting problem. Each section includes code implementations and explanations of the algorithms' logic and steps. The report is submitted by Shah Jamil Ahmed to the Department of Computer Science Engineering at BUBT.

Uploaded by

donjamil9383
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Shah Jamil Ahmed ID:20234103015

BANGLADESH UNIVERSITY OF BUSINESS & TECHNOLOGY


(BUBT)

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

LAB REPORTS - 04
COURSE TITLE- Algorithms Lab
COURSE CODE- CSE 232

Submitted To:
Md. Sajid Ahmed Chowdhury
Lecturer
Department of CSE
BUBT
Submitted By:

NAME: Shah Jamil Ahmed


ID: 20234103015
INTAKE: 52(DAY)
SECTION: 01

Date of Submission: 20th February 2025


Index
1. Greedy Algorithm -------------------------------------------- 1
2. Fractional Knapsack Problem ----------------------------- 1
2.1 Step-by-Step Solution Using a Greedy Algorithm --- 1
2.2 Example ---------------------------------------------------- 2
2.3 Code --------------------------------------------------------- 3
3. Activity Selection Problem --------------------------------- 3
3.1 Step-by-Step Solution Using a Greedy Algorithm ----------------- 3
3.2 Example ----------------------------------------------------- 3
4. Problem 1: Fractional Knapsack --------------------------- 4
5. Problem 2: Maximum Units on a Truck ----------------- 5
6. Problem 3: Minimum Number of Arrows to Burst Balloons ------------ 5
CODE Task - 01

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// Function to compare items based on value-to-weight ratio


bool compare(vector<int> &a, vector<int> &b) {
double ratio1 = (double)a[1] / a[0]; // value/weight
double ratio2 = (double)b[1] / b[0]; // value/weight
return ratio1 > ratio2; // Sort in decreasing order
}

// Function to solve Fractional Knapsack problem


double fractionalKnapsack(vector<vector<int>> &items, int capacity) {
// Sort items in decreasing order of value-to-weight ratio
sort(items.begin(), items.end(), compare);

double totalValue = 0.0; // Stores the total value in knapsack


for (const auto &item : items) {
int weight = item[0];
int value = item[1];

if (capacity >= weight) {


// If full item can be taken, take it
totalValue += value;
capacity -= weight;
} else {
// Take fraction of the remaining capacity
totalValue += value * ((double)capacity / weight);
return value;
break;
}
}

int main() {
int capacity = 10; // Knapsack capacity

// Items represented as {weight, value}


vector<vector<int>> items = {
{30, 500}

};

double maxValue = fractionalKnapsack(items, capacity);


cout << "Item with " << maxValue << " profit"<< endl;

return 0;
}

1
Explanation:

This program implements the Fractional Knapsack Problem using a greedy algorithm. The goal is to
maximize the total value of items that can be carried in a knapsack with a limited capacity. The greedy approach
ensures that the items with the highest value-to-weight ratio are taken first, either fully or partially, depending
on the remaining capacity of the knapsack.

1. Compare Function:

• The compare function is used to sort the items in decreasing order based on their value-to-weight ratio.
• ratio1 and ratio2 calculate the value-to-weight ratio for each item.
• The function returns true if the ratio of the first item is greater than that of the second item, ensuring
that the items are sorted in descending order of their efficiency (value per unit weight).

2. Fractional Knapsack Function:

• The function begins by sorting the items based on their value-to-weight ratio using the compare
function.
• It then iterates over the sorted list of items:
o Full Item: If the knapsack has enough remaining capacity to carry the full item, it adds the item's
value to the total value and reduces the knapsack’s capacity by the item's weight.
o Fractional Item: If the knapsack cannot carry the full item, it takes a fraction of the item,
calculates the proportional value that fits in the remaining capacity, and adds it to the total value.
The function then returns the total accumulated value after taking the fraction.
• The total value is returned as the maximum profit that the knapsack can carry.

3. Main Function:

• The main function initializes the capacity of the knapsack and defines a list of items, where each item is
represented by a pair of integers—its weight and value.
• It then calls the fractionalKnapsack function to calculate the maximum total value the knapsack can
carry, given the capacity and items.
• Finally, it prints the result, showing the total value or profit of the items that can be taken in the
knapsack.

2
CODE Task - 02
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// Function to compare items based on value-to-weight ratio


bool compare(vector<int> &a, vector<int> &b) {
double ratio1 = a[1] ; // value/weight
double ratio2 = b[1] ; // value/weight
return ratio1 > ratio2; // Sort in decreasing order
}

// Function to solve Fractional Knapsack problem


double fractionalKnapsack(vector<vector<int>> &items, int capacity) {
// Sort items in decreasing order of value-to-weight ratio
sort(items.begin(), items.end(), compare);

double totalValue = 0.0; // Stores the total value in knapsack


for (const auto &item : items) {
int weight = item[0];
int value = item[1];

if (capacity >= weight) {


// If full item can be taken, take it
totalValue += weight*value;
capacity -= weight;

}else
{

totalValue += value * capacity;


break;
}
}
return totalValue;
}

int main() {
int capacity = 10; // Knapsack capacity

// Items represented as {weight, value}


vector<vector<int>> items = {
{5, 10},
{2, 5},
{4, 7},
{3,9}
};
3
double maxValue = fractionalKnapsack(items, capacity);
cout << "Maximum value in Knapsack = " << maxValue << endl;

return 0;
}

Explanation:

This program implements the Fractional Knapsack Problem using a greedy algorithm. The aim is to
maximize the value of items that can be carried in a knapsack, where items can be taken fractionally based on
their value-to-weight ratio. This approach allows us to pick items in order of their efficiency (i.e., value per unit
weight), starting with the most valuable per unit weight.

1. Compare Function:

• The compare function is used to sort the items based on their value-to-weight ratio.
• The value-to-weight ratio is represented by the second element (value) in each item, but the weight (first
element) is not being utilized in the code for comparison in the current version.
• The function compares the value of each item (ratio1 and ratio2), sorting the items in decreasing
order of their value. This ensures that the most valuable items are processed first.

2. Fractional Knapsack Function:

• Sorting: The function begins by sorting the items in decreasing order of their value-to-weight ratio
using the compare function.
• Processing Items:
o The loop iterates through the sorted list of items.
o Full Item: If the knapsack has enough remaining capacity to carry the full item, it adds the
product of the item's weight and value to the total value (this is a mistake in the code, it should
ideally add value to the total value).
o Partial Item: If the knapsack cannot carry the full item, it takes the fraction of the item that can
fit in the remaining capacity and adds the product of the value and remaining capacity to the
total value. Once a partial item is taken, the loop terminates.
• The function returns the totalValue, representing the maximum value the knapsack can carry.

3. Main Function:

• The main function initializes the capacity of the knapsack and defines a set of items. Each item is
represented as a pair of integers, where the first integer is the weight and the second is the value.
• It then calls the fractionalKnapsack function to calculate the total maximum value the knapsack can
carry.
• Finally, it prints the result, showing the total value that can be accommodated in the knapsack.

4
CODE Task - 03

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int findMinArrows(vector<vector<int>>& points) {


// Sort the balloons by their end point
sort(points.begin(), points.end(), [](const vector<int>& a, const vector<int>& b) {
return a[1] < b[1];
});

int arrows = 1; // Start with one arrow for the first balloon
int lastArrow = points[0][1]; // Shoot the first arrow at the end of the first
balloon

// Iterate through the balloons


for (int i = 1; i < points.size(); i++) {
// If the current balloon starts after the last arrow's position
if (points[i][0] > lastArrow) {
arrows++; // We need a new arrow for this balloon
lastArrow = points[i][1]; // Shoot the new arrow at this balloon's end
}
}

return arrows;
}

int main() {
vector<vector<int>> points1 = {{10, 16}, {2, 8}, {1, 6}, {7, 12}};
vector<vector<int>> points2 = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
vector<vector<int>> points3 = {{1, 2}, {2, 3}, {3, 4}, {4, 5}};

cout << "Minimum arrows for points1: " << findMinArrows(points1) << endl;
cout << "Minimum arrows for points2: " << findMinArrows(points2) << endl;
cout << "Minimum arrows for points3: " << findMinArrows(points3) << endl;

return 0;
}

5
Explanation:

This code solves the minimum number of arrows needed to burst all the balloons using a greedy
algorithm. The goal is to minimize the number of arrows required to burst all balloons represented by intervals
in a 2D array. Each balloon is defined by a pair of integers [xstart, xend], where xstart is the start of the
balloon's horizontal diameter and xend is the end.

Steps in the Code:

1. Sorting the Balloons:


o The code first sorts the balloons based on their end points (xend) in ascending order. This is a
key part of the greedy approach: by sorting based on the end point, we ensure that we shoot
arrows in a way that bursts as many balloons as possible with each arrow.
o The sorting step is important because, if we place an arrow at the end of one balloon, it can
potentially burst all overlapping balloons that start before or at the same position as the arrow's
placement.
2. Greedy Arrow Selection:
o After sorting, the algorithm iterates over the sorted list of balloons.
o The strategy is to always shoot an arrow at the end point (xend) of the current balloon if it does
not overlap with the last balloon the arrow burst.
o If a balloon’s start point (xstart) is after the last arrow’s position, we need a new arrow to burst
this balloon, so the count of arrows is increased.
3. Arrow Counting:
o The variable arrows keeps track of how many arrows are shot.
o Initially, we assume one arrow is needed for the first balloon.
o As we move through the list of balloons, we check if the current balloon can be burst by the
same arrow that was used for the previous balloon. If not, we shoot a new arrow.
4. Final Result:
o After processing all balloons, the variable arrows holds the minimum number of arrows required
to burst all the balloons.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy