[LeetCode] Minimize the Maximum Edge Weight of Graph

3419. Minimize the Maximum Edge Weight of Graph

You are given two integers, n and threshold, as well as a directed weighted graph of n nodes numbered from 0 to n - 1. The graph is represented by a 2D integer array edges, where edges[i] = [Ai, Bi, Wi] indicates that there is an edge going from node Ai to node Bi with weight Wi.

You have to remove some edges from this graph (possibly none), so that it satisfies the following conditions:

  • Node 0 must be reachable from all other nodes.
  • The maximum edge weight in the resulting graph is minimized.
  • Each node has at most threshold outgoing edges.

Return the minimum possible value of the maximum edge weight after removing the necessary edges. If it is impossible for all conditions to be satisfied, 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
class Solution {
bool helper(vector<vector<pair<int,int>>>& adj, int x) {
vector<bool> vis(adj.size());
queue<int> q;
int cnt = adj.size();
auto push = [&](int u) {
if(!vis[u]) {
vis[u] = true;
cnt--;
q.push(u);
}
};
push(0);
while(q.size()) {
int u = q.front(); q.pop();
for(auto& [w,v] : adj[u]) {
if(w > x) break;
push(v);
}
}

return cnt == 0;
}
public:
int minMaxWeight(int n, vector<vector<int>>& edges, int threshold) {
vector<vector<pair<int,int>>> adj(n);
for(auto& e : edges) {
int v = e[0], u = e[1], w = e[2];
adj[u].push_back({w,v});
}
for(int i = 0; i < n; i++) sort(begin(adj[i]), end(adj[i]));
long long l = 0, r = INT_MAX - 1, res = INT_MAX;
while(l <= r) {
int m = l + (r - l) / 2;
bool ok = helper(adj,m);
if(ok) {
res = m;
r = m - 1;
} else l = m + 1;
}
return res == INT_MAX ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/01/12/PS/LeetCode/minimize-the-maximum-edge-weight-of-graph/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.