Python coding

Reachable using only short roads

There are n places numbered 0 to n - 1 and two-way roads, each [a, b, length]. Each query [start, goal, limit] asks: can you get from start to goal using only roads strictly shorter than limit? Return one boolean per query, in the order given. A place always reaches itself. Several roads may join the same pair, and a road may loop back to its own place.

There can be thousands of roads and queries, so a fresh search for every query is too slow.

Besides the tests, one large input (2,000 places, 3,998 roads, 1,000 queries) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • reachable_below(4, [[0,1,3],[1,2,5],[2,3,2],[0,3,9]], [[0,2,6],[0,2,5],[0,3,6],[3,1,4]]) → [true,false,true,false]
  • reachable_below(3, [[0,1,4],[0,1,2]], [[0,1,3],[0,1,2],[1,2,100]]) → [true,false,false]
  • reachable_below(5, [[0,1,10],[1,2,1],[2,3,7],[3,4,3],[0,4,4]], [[1,4,8],[1,4,7],[0,2,11],[2,4,5],[0,3,5]]) → [true,false,true,false,true]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

A search per query repeats nearly the same work every time. Notice that a higher limit only ever adds roads, and adding is exactly what union-find does well.

Hint 2

Answer offline: sort the roads by length and the queries by limit. Before answering a query, union every road shorter than its limit that is not open yet; then compare find(start) and find(goal).

Hint 3

A pointer into the sorted roads only moves forward, so each road is opened once in total. Sort the query indexes, not the queries, so every answer goes back to its original position.

Solution and why it works
pythonO(E log E + Q log Q + (E + Q)·α(n)), E roads, Q queries · O(n + E + Q)
def reachable_below(n: int, roads: list[list[int]], queries: list[list[int]]) -> list[bool]:
    parent, size = list(range(n)), [1] * n

    def find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]        # path halving
            x = parent[x]
        return x

    roads = sorted(roads, key=lambda road: road[2])
    answers, i = [False] * len(queries), 0
    for q in sorted(range(len(queries)), key=lambda q: queries[q][2]):    # smallest limit first
        start, goal, limit = queries[q]
        while i < len(roads) and roads[i][2] < limit:      # open every road shorter than this limit
            ra, rb = find(roads[i][0]), find(roads[i][1])
            if ra != rb:
                if size[ra] < size[rb]:
                    ra, rb = rb, ra
                parent[rb] = ra
                size[ra] += size[rb]
            i += 1
        answers[q] = find(start) == find(goal)              # answer in the original order
    return answers

A higher limit only adds roads, and union-find handles additions well. So answer the queries offline: sort them by limit, sweep the roads in order of length, and union each road as soon as the current limit exceeds it; a query is then just find(start) == find(goal). Every road is unioned once in total instead of once per query. Traps: the limit is strict (a road of length limit stays closed), and sorting the queries themselves loses their order: sort their indexes and write each answer back.