Hardik 1.3 Ap
Hardik 1.3 Ap
Hardik 1.3 Ap
Experiment 1.3
1. Aim:
Understand the concept of Heap model.
2. Problems:
a: Last Stone Weight
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.
b: Distant Barcodes
In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i].
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return
any answer, and it is guaranteed an answer exists.
3. Code:
a:
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
priority_queue<int> max_heap;
for (int stone : stones) {
max_heap.push(stone);
}
while (max_heap.size() > 1) {
int y = max_heap.top(); max_heap.pop();
int x = max_heap.top(); max_heap.pop();
if (x != y) {
max_heap.push(y - x);
}
}
return max_heap.empty() ? 0 : max_heap.top();
}
};
b:
class Solution {
public:
vector<int> rearrangeBarcodes(vector<int>& barcodes) {
unordered_map<int, int> frequencyMap;
priority_queue<pair<int, int>> maxHeap;
for (int barcode : barcodes) {
frequencyMap[barcode]++;
}
for (auto& entry : frequencyMap) {
maxHeap.push({entry.second, entry.first});
}
vector<int> result(barcodes.size());
int index = 0;
while (!maxHeap.empty()) {
auto [freq1, barcode1] = maxHeap.top();
maxHeap.pop();
result[index] = barcode1;
index++;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
if (!maxHeap.empty()) {
auto [freq2, barcode2] = maxHeap.top();
maxHeap.pop();
result[index] = barcode2;
index++;
if (--freq2 > 0) {
maxHeap.push({freq2, barcode2});
}
}
if (--freq1 > 0) {
maxHeap.push({freq1, barcode1});
}
}
return result;
}
};
4. Output:
a.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
b.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING