Problem · Graph
Minimum-Cost Meeting City
Learn this problemProblem statement
An undirected, unweighted graph represents n cities numbered from 0 to n - 1. Travelers start at cities x and y. They may travel separately to a meeting city m, then ride together from m to destination.
The cost of choosing m is dist(x, m) + dist(y, m) + dist(m, destination), so the shared final route is counted once.
Return the meeting city with minimum cost. If several cities have the same minimum cost, return the smallest city index. Return -1 if no city is reachable from both travelers and can reach destination.
Function
minimumCostMeetingCity(n: int, edges: int[][], x: int, y: int, destination: int) → intExamples
Example 1
n = 7edges = [[0,2],[1,2],[2,3],[3,6],[0,4],[1,4],[4,5],[5,6]]x = 0y = 1destination = 6return = 2Meeting at city 2 costs 1 + 1 + 2 = 4. Meeting at city 4 also costs 4, so the smaller city index 2 wins the tie.
Example 2
n = 4edges = [[0,1],[2,3]]x = 0y = 2destination = 3return = -1The travelers start in different connected components, so no valid meeting city exists.
Constraints
1 <= n <= 2000000 <= edges.length <= 200000- Every row of
edgesis[u, v]with0 <= u, v < nandu != v. 0 <= x, y, destination < n