Skip to content

1928. Minimum Cost to Reach Destination in Time 👍

  • Time: $O((|V| + |E|)\log |V|)$
  • Space: $O(|E| + |V|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
 public:
  int minCost(int maxTime, vector<vector<int>>& edges,
              vector<int>& passingFees) {
    const int n = passingFees.size();
    vector<vector<pair<int, int>>> graph(n);

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      const int w = edge[2];
      graph[u].emplace_back(v, w);
      graph[v].emplace_back(u, w);
    }

    return dijkstra(graph, 0, n - 1, maxTime, passingFees);
  }

 private:
  int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst,
               int maxTime, const vector<int>& passingFees) {
    // cost[i] := the minimum cost to reach the i-th city
    vector<int> cost(graph.size(), INT_MAX);
    // dist[i] := the minimum time to reach the i-th city
    vector<int> dist(graph.size(), maxTime + 1);

    cost[src] = passingFees[src];
    dist[src] = 0;
    using T = tuple<int, int, int>;  // (cost[u], dist[u], u)
    priority_queue<T, vector<T>, greater<>> minHeap;
    minHeap.emplace(cost[src], dist[src], src);

    while (!minHeap.empty()) {
      const auto [currCost, d, u] = minHeap.top();
      minHeap.pop();
      if (u == dst)
        return cost[dst];
      if (d > dist[u] && currCost > cost[u])
        continue;
      for (const auto& [v, w] : graph[u]) {
        if (d + w > maxTime)
          continue;
        // Go from u -> v.
        if (currCost + passingFees[v] < cost[v]) {
          cost[v] = currCost + passingFees[v];
          dist[v] = d + w;
          minHeap.emplace(cost[v], dist[v], v);
        } else if (d + w < dist[v]) {
          dist[v] = d + w;
          minHeap.emplace(currCost + passingFees[v], dist[v], v);
        }
      }
    }

    return -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
  public int minCost(int maxTime, int[][] edges, int[] passingFees) {
    final int n = passingFees.length;
    List<Pair<Integer, Integer>>[] graph = new List[n];

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      final int t = edge[2];
      graph[u].add(new Pair<>(v, t));
      graph[v].add(new Pair<>(u, t));
    }

    return dijkstra(graph, 0, n - 1, maxTime, passingFees);
  }

  private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst, int maxTime,
                       int[] passingFees) {
    int[] cost = new int[graph.length]; // cost[i] := the minimum cost to reach the i-th city
    int[] dist = new int[graph.length]; // dist[i] := the minimum distance to reach the i-th city
    Arrays.fill(cost, Integer.MAX_VALUE);
    Arrays.fill(dist, maxTime + 1);

    cost[0] = passingFees[0];
    dist[0] = 0;
    Queue<int[]> minHeap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0])) {
      { offer(new int[] {cost[src], dist[src], src}); } // (cost[u], dist[u], u)
    };

    while (!minHeap.isEmpty()) {
      final int currCost = minHeap.peek()[0];
      final int d = minHeap.peek()[1];
      final int u = minHeap.poll()[2];
      if (u == dst)
        return cost[dst];
      if (d > dist[u] && currCost > cost[u])
        continue;
      for (Pair<Integer, Integer> pair : graph[u]) {
        final int v = pair.getKey();
        final int w = pair.getValue();
        if (d + w > maxTime)
          continue;
        // Go from x -> y
        if (currCost + passingFees[v] < cost[v]) {
          cost[v] = currCost + passingFees[v];
          dist[v] = d + w;
          minHeap.offer(new int[] {cost[v], dist[v], v});
        } else if (d + w < dist[v]) {
          dist[v] = d + w;
          minHeap.offer(new int[] {currCost + passingFees[v], dist[v], v});
        }
      }
    }

    return -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution:
  def minCost(
      self,
      maxTime: int,
      edges: list[list[int]],
      passingFees: list[int],
  ) -> int:
    n = len(passingFees)
    graph = [[] for _ in range(n)]

    for u, v, w in edges:
      graph[u].append((v, w))
      graph[v].append((u, w))

    return self._dijkstra(graph, 0, n - 1, maxTime, passingFees)

  def _dijkstra(
      self,
      graph: list[list[tuple[int, int]]],
      src: int,
      dst: int,
      maxTime: int,
      passingFees: list[int],
  ) -> int:
    # cost[i] := the minimum cost to reach the i-th city
    cost = [math.inf] * len(graph)
    # dist[i] := the minimum time to reach the i-th city
    dist = [maxTime + 1] * len(graph)

    cost[src] = passingFees[src]
    dist[src] = 0
    minHeap = [(cost[src], dist[src], src)]  # (cost[u], dist[u], u)

    while minHeap:
      currCost, d, u = heapq.heappop(minHeap)
      if u == dst:
        return cost[dst]
      if d > dist[u] and currCost > cost[u]:
        continue
      for v, w in graph[u]:
        if d + w > maxTime:
          continue
        # Go from u -> v.
        if currCost + passingFees[v] < cost[v]:
          cost[v] = currCost + passingFees[v]
          dist[v] = d + w
          heapq.heappush(minHeap, (cost[v], dist[v], v))
        elif d + w < dist[v]:
          dist[v] = d + w
          heapq.heappush(minHeap, (currCost + passingFees[v], dist[v], v))

    return -1