You are on page 1of 3

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

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.

3. Algo. /Approach and output:


1st:

import java.util.PriorityQueue;

public class Solution {


public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
for (int stone : stones) {
pq.add(stone);
}
while (pq.size() != 1) {
int a = pq.poll();
int b = pq.poll();
int c = a - b;
pq.add(c);
}
return pq.peek();
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

}
}

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<>());
}

for (int[] flight : flights) {


adj.get(flight[0]).add(new int[]{flight[1], flight[2]});
}

Queue<int[]> q = new LinkedList<>();


int[] dist = new int[n];
Arrays.fill(dist, 1_000_000);
dist[src] = 0;

q.offer(new int[]{0, src, 0});


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

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;
}
}

You might also like