← 返回 ibm 的题目列表Minimum Link Reallocation to Connect Repositories
类型:qbank
Given `link_nodes` repositories and existing undirected sync links, compute the minimum number of existing links that must be reassigned so every repository becomes connected. If there are fewer than `n - 1` links, return `-1`.
Requirements
Input:
link_nodes: number of repositories, numbered from 1 to link_nodes.
link_from[]: start endpoints of existing undirected links.
link_to[]: end endpoints of existing undirected links.
Reassignment operation: delete one existing link and reconnect it between any two repositories.
Output: the minimum number of reassignments required to make all repositories part of one connected component.
If the number of links is less than link_nodes - 1, return -1.
Examples
link_nodes = 4
link_from = [1, 1, 3]
link_to = [2, 3, 2]
Output: 1
The initial components are {1,2,3} and {4}; one redundant edge can be reassigned.
link_nodes = 4
link_from = [1, 2]
link_to = [3, 4]
Output: -1
There are only two links, fewer than 4 - 1.
Notes
The core answer is component_count - 1 when there are enough edges.
Use DFS/BFS or union-find to count connected components.
The impossibility check must happen before relying on duplicate or cycle edges: any connected graph on n nodes needs at least n - 1 edges.
Preparation
Implement both union-find and DFS/BFS versions, including 1-index to 0-index conversion tests.
Memorise the proof: with at least n - 1 edges, every extra edge inside a component can be repurposed, so the only remaining count is components - 1.