Professional Documents
Culture Documents
New - AP-2 - Exp - 3 - 21BCS10816 - Ridhima - CC-629
New - AP-2 - Exp - 3 - 21BCS10816 - Ridhima - CC-629
Experiment 1.3
Student Name: Ridhima UID: 21BCS10816
Branch: BE-CSE Section/Group: CC-629-A
Semester: 6th Date of Performance: 30-01-2024
Subject Name: Advance Programming-2 Subject Code: 21CSP-251
1. Aim:
• To Solve the Last Stone Weight.
• To Solve the Cheapest Flight Booking with K stops.
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.
• There are n cities connected by some number of flights. You are given an
array flights where flights[i] = [fromi, toi, pricei] indicates that there is a
flight from city fromi to city toi with cost pricei.
import java.util.PriorityQueue;
}
}
2nd:
import java.util.*;
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
List<List<int[]>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
while (!q.isEmpty()) {
int[] front = q.poll();
int stops = front[0];
int cost = front[2];
int node = front[1];
if (stops > k) {
continue;
}
for (int[] it : adj.get(node)) {
if (cost + it[1] < dist[it[0]] && stops <= k) {
dist[it[0]] = cost + it[1];
q.offer(new int[]{stops + 1, it[0], dist[it[0]});
}
}
}
if (dist[dst] != 1_000_000) {
return dist[dst];
}
return -1;
}
}