Minimum Distance Matching in a Forest
Problem statement
edges describes an undirected forest with uniquely labeled integer nodes. Match every label in left to a distinct label in right.
The cost of a pair is the number of forest edges on their path. Nodes in different trees cannot be paired. right may contain extra labels that remain unused.
Return the minimum total distance of a valid one-to-one matching, or -1 when no matching covers every label in left.
Function
minimumForestMatchingDistance(edges: int[][], left: int[], right: int[]) → intExamples
Example 1
edges = [[1,2],[2,3],[2,4],[5,6]]left = [1,3]right = [4,2]return = 3Either pairing has total distance 3.
Example 2
edges = [[1,2],[3,4]]left = [1,3]right = [4,2]return = 2Pair 1 with 2 and 3 with 4; the right-array order need not be preserved.
Example 3
edges = [[1,2],[3,4]]left = [1,2]right = [3,4]return = -1Every possible pair crosses disconnected trees.
Constraints
1 <= edges.length <= 200000.- The graph is an undirected forest with no duplicate edge.
- Every query label appears in at least one edge.
1 <= left.length <= right.length <= 12.- Labels within each query array are unique.