Computer Science & Engineering: Department of
Computer Science & Engineering: Department of
Experiment-1.3
Student Name: Kunal Shaw UID: 21BCS2144
Branch: BE-CSE Section: 608-A
Subject Name: Advance programming-2 Subject Code: 21CSP-351
Aim:
• Last stone weight
• Cheapest flight with K stops
Algorithm:
A. Last Stone Weight :
• First, we create a priority queue in C++ using std::priority_queue class to keep
track of the maximum elements in the input vector.
• We initialize this priority queue with all the elements of the input vector using
priority_queue constructor that takes two iterators pointing to the beginning
and end of the input vector.
• Next, we start a loop that will execute until there is only one element left in the
priority queue. In each iteration of the loop, we perform the following steps:
1. Pop the largest element (x) from the priority queue using pq.top() and
store it in a variable x.
2. Pop the second-largest element (y) from the priority queue
using pq.top() again and store it in a variable y.
3. Calculate their difference (x-y) and if the difference is not zero, push it
back into the priority queue using pq.push(x-y).
• After the loop has finished executing, we check if the priority queue is empty
or not using pq.empty(). If the priority queue is empty, then it means all stones
have been destroyed, and we return 0 as the last stone weight. Otherwise, we
use pq.top() to get the top element of the priority queue, which represents the
last remaining stone weight, and return
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> pq; //max heap
for(int i=0; i<stones.size(); i++){
pq.push(stones[i]);
}
while(pq.size()>1){
int x=pq.top();
pq.pop();
int y=pq.top();
pq.pop();
if(x>y){
pq.push(x-y);
}
}
return pq.empty() ? 0:pq.top();
}
};
Output(A):
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Code(B):
class Solution {
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int
dst, int k) {
vector<pair<int, int>> adj[n];
for(auto it: flights){
adj[it[0]].push_back({it[1], it[2]});
while(!q.empty()){
auto it =q.front();
q.pop();
int stops = it.first;
int node = it.second.first;
int cost = it.second.second;
if(stops> k) continue;
for(auto iter: adj[node]){
int adjNode = iter.first;
int edW = iter.second;
Output(B):
Time Complexity :
A. O(log n)
B. O(n)