# Solution For Minimum Fuel Cost To Report To The Capital

Problem Statement:

Given a map of cities connected by roads and the cost of fuel to travel from one city to another, the minimum fuel cost to report to the capital is to be computed. The fuel cost to report to a city is the cost of fuel multiplied by the distance from that city to the capital. At any city, you can refuel the car with an unlimited amount of fuel, but the car has limited tank capacity.

Solution:

We can solve this problem using Dijkstra’s Algorithm.

In Dijkstra’s algorithm, we maintain a priority queue to keep track of the next shortest distance node from the source node. Initially, the distance of the source node is set to 0 and all other nodes are set to infinity. We extract the node with the shortest distance from the priority queue, and then update the distance of its neighbors. We repeat this process until all nodes are visited.

In this problem, we can modify Dijkstra’s Algorithm to keep track of the minimum fuel cost to report to the capital. We can maintain a priority queue to keep track of the next city with the minimum fuel cost to report to the capital. Initially, we set the fuel cost of the capital to 0, and fuel costs of all other cities to infinity. We extract the city with the minimum fuel cost from the priority queue, and then update the fuel costs of its neighbors based on the fuel cost of the current city, cost of fuel required to travel from the current city to its neighbors, and distance of the neighbors from the capital.

Algorithm:

- Initialize the minimum fuel cost table with 0 for the capital and infinity for all other cities.
- Add the capital to the priority queue with its fuel cost as 0.
- While the priority queue is not empty, extract the city with the minimum fuel cost.
- For each neighbor of the current city, calculate the fuel cost of traveling to the neighbor based on the current city’s fuel cost, the fuel cost required to travel from the current city to the neighbor, and the distance of the neighbor from the capital.
- If the calculated fuel cost is less than the existing fuel cost of the neighbor, update the fuel cost of the neighbor with the calculated fuel cost and add the neighbor to the priority queue.

Complexity Analysis:

The time complexity of our algorithm can be calculated as O(ElogV), where E is the number of edges and V is the number of vertices. The logarithmic term arises from the priority queue operations.

The space complexity of our algorithm is O(V), where V is the number of vertices. We need to store the fuel cost table and priority queue.

Code:

The following is the Python code for our algorithm:

import heapq

from typing import List

def minFuelCost(n: int, roads: List[List[int]], fuelPrices: List[int]) -> int:

# Create adjacency list and fuel cost table

adj = [[] for _ in range(n)]
fuel_cost = [float(‘inf’) for _ in range(n)]
for u, v, d in roads:

adj[u-1].append((v-1, d))

adj[v-1].append((u-1, d))

```
# Initialize the fuel cost table and priority queue
fuel_cost[0] = 0
pq = [(0, 0)]
# Dijkstra's algorithm with fuel cost modification
while pq:
cost, u = heapq.heappop(pq)
if fuel_cost[u] < cost:
continue
for v, d in adj[u]:
fuel_needed = d * fuelPrices[u]
fc = cost + fuel_needed * (v != 0)
if fc < fuel_cost[v]:
fuel_cost[v] = fc
heapq.heappush(pq, (fc, v))
# Return the fuel cost to reach the capital
return fuel_cost[-1]
```

## Step by Step Implementation For Minimum Fuel Cost To Report To The Capital

class Solution { public int mincostToHireWorkers(int[] quality, int[] wage, int K) { int N = quality.length; Worker[] workers = new Worker[N]; for (int i = 0; i < N; ++i) workers[i] = new Worker(quality[i], wage[i]); Arrays.sort(workers); double ans = 1e9; int sumq = 0; PriorityQueuepq = new PriorityQueue(); for (Worker worker: workers) { sumq += worker.quality; pq.add(-worker.quality); if (pq.size() > K) sumq += pq.poll(); if (pq.size() == K) ans = Math.min(ans, sumq * worker.ratio()); } return (int) Math.round(ans); } } class Worker implements Comparable { public int quality, wage; public Worker(int q, int w) { quality = q; wage = w; } public double ratio() { return (double) wage / quality; } public int compareTo(Worker other) { return Double.compare(ratio(), other.ratio()); } }

def minFuelCost(stations, target): # Create a min heap to store the stations # according to their distance from the target heap = [] for station in stations: heapq.heappush(heap, (abs(station - target), station)) # Initialize result result = 0 # While there are stations in the heap while heap: # Extract station with minimum distance # from the target _, curr_station = heapq.heappop(heap) # Find the fuel required to reach this station fuel_required = abs(curr_station - target) # Add this fuel to the result result += fuel_required # Update the target to be this station target = curr_station return result

// minimum-fuel-cost-to-report-to-the-capital // There are n cities numbered from 0 to n-1. You are given directions to all these cities as an array paths where paths[i] = [cityAi, cityBi] means there exists a bidirectional path going from cityAi to cityBi. The cost of the path is the sum of the costs of all the edges in the path. // Return the minimum cost to report to the capital. // You can start and stop at any city, you can revisit cities multiple times, and you can re-use edges. // Example 1: // Input: n = 4, paths = [[0,1],[1,2],[2,0],[1,3]] // Output: 4 // Explanation: One possible path is [0,1,2,3] // This path has a weight of 4 since we can first go from city 0 to city 1 for a cost of 1, then go to city 2 for a cost of 2, and finally go to city 3 for a cost of 1. // Example 2: // Input: n = 6, paths = [[0,1],[0,2],[2,3],[2,4],[2,5]] // Output: 0 // Explanation: We start at city 0 with a cost of 0. We can visit all the cities in any order, and the total cost will be 0 since there are no paths. // Example 3: // Input: n = 5, paths = [[1,2],[2,3],[3,4],[4,5],[1,5]] // Output: 4 // Explanation: One possible path is [1,2,3,4,5] // This path has a weight of 4 since we can first go from city 1 to city 2 for a cost of 1, then go to city 3 for a cost of 2, then go to city 4 for a cost of 3, and finally go to city 5 for a cost of 1. // Constraints: // 1 <= n <= 100 // cost.length == n // cost[i].length == n // 1 <= cost[i][j] <= 1000 // paths.length == n-1 // paths[i].length == 2 // 0 <= cityAi, cityBi <= n-1 // cityAi != cityBi // All pairs (cityAi, cityBi) are distinct.

int minCostToReport(vector>& roads, int n) { // initialize cost and visited arrays vector cost(n, INT_MAX); vector visited(n, false); // set cost of starting node to 0 cost[0] = 0; // run Dijkstra's algorithm while (true) { // find node with smallest cost that has not been visited int minNode = -1; for (int i = 0; i < n; i++) { if (!visited[i] && (minNode == -1 || cost[i] < cost[minNode])) { minNode = i; } } // if all nodes have been visited, break out of loop if (minNode == -1) break; // mark node as visited visited[minNode] = true; // update cost of neighbors for (auto& road : roads) { if (road[0] == minNode) { cost[road[1]] = min(cost[road[1]], cost[minNode] + road[2]); } } } // return cost of reporting to capital return cost[n - 1]; }

public class Solution { public int FindCheapestPrice(int n, int[][] flights, int src, int dst, int K) { // create a map to store all the flights var map = new Dictionary>(); foreach (var flight in flights) { if (!map.ContainsKey(flight[0])) { map.Add(flight[0], new List ()); } map[flight[0]].Add(new int[] {flight[1], flight[2]}); } // create a min heap to store the current cheapest flights var heap = new SortedSet (); heap.Add(new int[] {0, src, K+1}); while (heap.Count != 0) { var top = heap.Min; heap.Remove(top); var price = top[0]; var city = top[1]; var stops = top[2]; if (city == dst) return price; if (stops > 0) { // get all the flights from the current city var flightsFromCity = map[city]; foreach (var flight in flightsFromCity) { var nextCity = flight[0]; var nextPrice = price + flight[1]; var nextStops = stops - 1; // add the flight to the heap if it's cheaper than the flights currently in the heap heap.Add(new int[] {nextPrice, nextCity, nextStops}); } } } return -1; } }