Engineering platform~40 min2s · 256 MBtarget O(m² α(n)) time, O(n + m) spaceclassic twin: lc-1489greedy · union-find
The engineering platform behind an app connects its data centres with network links. Each possible link has a cost. The team builds a cheapest set of links that lets every centre reach every other centre. Several different sets can have the same lowest cost.
For each link the team asks one question. A link that every cheapest set uses is a must-have link. A link that some cheapest sets use and others do not is an optional link.
Write classify_links(nodes, links).
nodes is the number of data centres, numbered 0 to nodes - 1.links[i] is [a, b, cost]: a possible link between two different centres a and b. Two links may join the same pair. The links connect all centres.nodes - 1 links, connects every centre, and has the lowest possible total cost.[must_have, optional]: how many links are in every cheapest set, and how many are in some cheapest sets but not all.Input: nodes = 5, links = [[0,1,1],[1,2,1],[0,2,1],[2,3,2],[3,4,3],[3,4,3],[2,4,5]]
Output: [1, 5]The cheapest total is 7. The solution tests each link twice: it builds the cheapest set without the link, and it builds the cheapest set with the link forced in.
| Link | Cost without it | Cost with it forced | Verdict |
|---|---|---|---|
0: [0,1,1] |
7 | 7 | optional |
1: [1,2,1] |
7 | 7 | optional |
2: [0,2,1] |
7 | 7 | optional |
3: [2,3,2] |
10 | 7 | must-have |
4: [3,4,3] |
7 | 7 | optional |
5: [3,4,3] |
7 | 7 | optional |
6: [2,4,5] |
7 | 9 | never used |
Input: nodes = 3, links = [[0,1,4],[1,2,7]]
Output: [2, 0]Both links are the only way to reach their centres.
Input: nodes = 4, links = [[0,1,3],[1,2,3],[2,3,3],[3,0,3]]
Output: [0, 4]Four equal links on a cycle: a cheapest set drops any one link, so each link is in some sets and not in others.
1 ≤ nodes ≤ 2000 ≤ len(links) ≤ 400, and every link is [a, b, cost] with 0 ≤ a, b < nodes, a ≠ b and 0 ≤ cost ≤ 1,000,000Listing every choice of 199 links out of 400 is far beyond any machine. But 400 links allow a rebuild for each link: 400 × 2 builds of about 400 steps each is 320,000 steps. A quadratic method is comfortable.