Problem Description
Given a directed, weighted graph with n nodes and a list of edges, remove some edges (possibly none) so that:
- Node 0 is reachable from every other node (i.e. for every node there exists a directed path to node 0).
- The maximum edge weight among the remaining edges is minimized.
- Each node has at most threshold outgoing edges in the remaining graph.
Return the minimum possible value of the maximum edge weight if such a subgraph exists, otherwise return -1.
Key Insights
- The connectivity requirement (every node must reach node 0) can be checked by reversing the graph and ensuring that starting from node 0 all nodes are reached.
- The degree constraint (each node has at most threshold outgoing edges) is automatically satisfied by choosing a spanning arborescence since every node (except 0) will use exactly one outgoing edge.
- With a fixed maximum allowed edge weight X, we can discard all edges with weight more than X and then check if the remaining (reversed) graph is connected from node 0.
- Using binary search over the range of edge weights efficiently determines the smallest maximum weight for which a valid subgraph exists.
Space and Time Complexity
Time Complexity: O(E * log(W)) where E is the number of edges and W is the range of edge weights.
Space Complexity: O(n + E) for storing the graph.
Solution
We solve the problem with binary search combined with a graph connectivity check:
- Define low and high as the minimum and maximum edge weights.
- For a given candidate mid value, consider only edges with weight <= mid.
- Reverse these edges (since connectivity from every node to 0 in the original is equivalent to 0 reaching every node in the reversed graph).
- Perform a DFS/BFS from node 0 in the reversed graph and see if all nodes are visited.
- If all nodes are reachable then mid is feasible and we try a smaller mid, otherwise, we need to allow larger edge weights.
- Return the smallest mid for which connectivity is achieved.
Since a spanning arborescence can be constructed (each node except 0 needing at most one outgoing edge) the threshold constraint is naturally satisfied as threshold ≥ 1.