Minimum Distance Excluding One Maximum Weighted Edge Problem
Description
LeetCode Problem 3778.
You are given a positive integer n and a 2D integer array edges, where edges[i] = [u_i, v_i, w_i].
There is a weighted connected simple undirected graph with n nodes labeled from 0 to n - 1. Each [u_i, v_i, w_i] in edges represents an edge between node u_i and node v_i with positive weight w_i.
The cost of a path is the sum of weights of the edges in the path, excluding the edge with the maximum weight. If there are multiple edges in the path with the maximum weight, only the first such edge is excluded.
Return an integer representing the minimum cost of a path going from node 0 to node n - 1.
Example 1:
Input: n = 5, edges = [[0,1,2],[1,2,7],[2,3,7],[3,4,4]]
Output: 13
Explanation:
There is only one path going from node 0 to node 4: 0 -> 1 -> 2 -> 3 -> 4.
The edge weights on this path are 2, 7, 7, and 4.
Excluding the first edge with maximum weight, which is 1 -> 2, the cost of this path is 2 + 7 + 4 = 13.
Example 2:
Input: n = 3, edges = [[0,1,1],[1,2,1],[0,2,50000]]
Output: 0
Explanation:
There are two paths going from node 0 to node 2:
- 0 -> 1 -> 2
The edge weights on this path are 1 and 1.
Excluding the first edge with maximum weight, which is 0 -> 1, the cost of this path is 1.
- 0 -> 2
The only edge weight on this path is 1.
Excluding the first edge with maximum weight, which is 0 -> 2, the cost of this path is 0.
The minimum cost is min(1, 0) = 0.
Constraints:
2 <= n <= 5 * 10^4n - 1 <= edges.length <= 10^9edges[i] = [u_i, v_i, w_i]0 <= u_i < v_i < n[u_i, v_i] != [u_j, v_j]1 <= w_i <= 5 * 10^4- The graph is connected.
Solution
Approach: Dijkstra's Algorithm
Excluding the maximum edge of a path is the best way to skip one edge, so the task is to find a path from 0 to n-1 in which one edge may be taken for free.
Run Dijkstra on states (node, used), where used says whether the free edge has been spent. dist[u][0] is the cheapest cost to reach u without using it and dist[u][1] is the cheapest cost once it has been used. From a state, each edge (v, w) leads to (v, used) with cost +w, and when used = 0 also to (v, 1) with cost +0. The answer is dist[n-1][1].
Complexity: time O(m log n), space O(n + m), where n and m are the numbers of nodes and edges.
from math import inf
from heapq import heappush, heappop
class Solution:
def minCostExcludingMax(self, n: int, edges: List[List[int]]) -> int:
g = [[] for _ in range(n)]
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
dist = [[inf] * 2 for _ in range(n)]
dist[0][0] = 0
pq = [(0, 0, 0)]
while pq:
cur, u, used = heappop(pq)
if cur > dist[u][used]:
continue
if u == n - 1 and used:
return cur
for v, w in g[u]:
nxt = cur + w
if nxt < dist[v][used]:
dist[v][used] = nxt
heappush(pq, (nxt, v, used))
if used == 0:
nxt = cur
if nxt < dist[v][1]:
dist[v][1] = nxt
heappush(pq, (nxt, v, 1))
return dist[n - 1][1]