You are on page 1of 4

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment 1.3

StudentName: Sushant Kumar UID:22BCS90002


Branch: CSE Section/Group:635-A
Semester: 6th DateofPerformance:05-02-2024
Subject Name: AP_ LAB
Subject Code: 21CSP 351

1) Task 1:
2) Aim: To demonstrate the concept of Heap model.

Objective: You are given an integer array heights representing the heights of buildings,
some bricks, and some ladders.
You start your journey from building 0 and move to the next building by possibly using
bricks or ladders.
While moving from building i to building i+1 (0-indexed),
• If the current building's height is greater than or equal to the next building's height, you
do not need a ladder or bricks.
• If the current building's height is less than the next building's height, you can either
use one ladder or (h[i+1] - h[i]) bricks.
Return the furthest building index (0-indexed) you can reach if you use the given ladders
and bricks optimally.

3) Program Code:
class Solution {
public:
int furthestBuilding(vector<int>& heights, int bricks, int ladders) {
priority_queue<int, vector<int>, greater<int>> minHeap;

for (int i = 1; i < heights.size(); ++i) {


const int diff = heights[i] - heights[i - 1];
if (diff <= 0)
continue;
minHeap.push(diff);
// If we run out of ladders, greedily use as less bricks as possible.
if (minHeap.size() > ladders)
bricks -= minHeap.top(), minHeap.pop();
if (bricks < 0)
return i - 1;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

return heights.size() - 1;
}
};

4) OUTPUT:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

1. Task-2

Objective: You are given an array of integers stones where stones[i] is the weight of
the ith stone.We are playing a game with the stones. On each turn, we choose
the heaviest two stones and smash them together. Suppose the heaviest two stones
have weights x and y with x <= y. The result of this smash is:
If x == y, both stones are destroyed, and
If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y
- x.
At the end of the game, there is at most one stone left.
Return the weight of the last remaining stone. If there are no stones left, return 0.

2. Program Code:

class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> pq{stones.begin(), stones.end()};

while (pq.size() >= 2) {


const int n1 = pq.top();
pq.pop();
const int n2 = pq.top();
pq.pop();
if (n1 != n2)
pq.push(n1 - n2);
}

return pq.empty() ? 0 : pq.top();


}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

3. OUTPUT :

Learning outcomes:

1) Differentiate between Max Heap and Min Heap structures.


2) Analyse the time and space complexities of various Heap operations.
3) Understand the HeapSort algorithm and its step-by-step execution.

You might also like