Professional Documents
Culture Documents
21BCS4422_Manohar-Chaudhary_1.3 AP
21BCS4422_Manohar-Chaudhary_1.3 AP
EXPERIMENT 1.3
I. Problem statement - 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.
II. Problem Statement- 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.
You are also given three integers src, dst, and k, return the cheapest price from
src to dst with at most k stops. If there is no such route, return -1.
2. Objective:
✓ Highlight the importance of concept of Heap model.
✓ Define the Heap model and its significance in computer science.
3. Code
1.
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
if len(stones) == 0:
return 0
return stones[0]
2.
from collections import defaultdict
class Solution:
def findCheapestPrice(self, n, flights, src, dst, k):
graph = defaultdict(list)
# Initialize dp array
dp = [[-1] * (k + 2) for _ in range(n)]
min_price = float('inf')
for neighbor, price in graph[src]:
cheap = dfs(neighbor, dst, k - 1)
if cheap != float('inf'):
min_price = min(min_price, cheap + price)
dp[src][k] = min_price
return min_price
# Example usage:
n = 3
flights = [[0,1,100],[1,2,100],[0,2,500]]
src = 0
dst = 2
k = 1
solution = Solution()
print(solution.findCheapestPrice(n, flights, src, dst, k))
4. OUTPUT
1.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
2.
5. Learning Outcomes :
✓ Understood what a Heap is and its representation in computer science.
✓ Implemented Heap-based solutions for finding kth largest/smallest elements and shortest paths in
graphs.
✓ Understood the trade-offs between using Heaps and alternative approaches in algorithm design.