Ctrl K

Walks Priced by AND

Hard
A city has n junctions numbered 0 to n - 1 and two-way roads roads, where roads[i] = [u, v, w] is a road between u and v with weight w. Two junctions may be linked by several roads. A walk is a sequence of roads in which each road starts where the previous one ended. A walk may use the same road or pass the same junction any number of times. The cost of a walk is the bitwise AND of the weights of all roads it uses. For each query queries[j] = [s, t], find the minimum cost of a walk from s to t, or -1 if t cannot be reached. Return the answers in query order.
Example 1
n=4, roads=[[0, 1, 6], [1, 2, 3], [2, 0, 7]], queries=[[0, 2], [1, 3]] → [2, -1]

From 0 to 2 it pays to use all three roads (0 → 1 → 2 → 0 → 2): 6 AND 3 AND 7 = 2. Junction 3 has no roads at all, so the second answer is -1.

Example 2
n=5, roads=[[0, 1, 12], [3, 4, 5], [3, 4, 9]], queries=[[1, 0], [4, 3], [2, 4]] → [12, 1, -1]

There is a single road of weight 12 between 0 and 1. Junctions 3 and 4 are joined by two roads and a walk may use both: 5 AND 9 = 1. Junction 2 is isolated.

Constraints
  • 2 ≤ n ≤ 10⁵
  • 0 ≤ len(roads) ≤ 10⁵
  • 0 ≤ u, v ≤ n - 1, u ≠ v
  • 0 ≤ w ≤ 10⁵
  • 1 ≤ len(queries) ≤ 10⁵
  • 0 ≤ s, t ≤ n - 1, s ≠ t
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWhich Machine to Cure HardWhich Machine to Unplug HardCell Levels by Rows and Columns HardScooter Trips Under a Road Limit HardConflicting Ratio Facts Hard
loading Python…
Input
n=4, roads=[[0, 1, 6], [1, 2, 3], [2, 0, 7]], queries=[[0, 2], [1, 3]]
Expected
[2, -1]

Run checks the first 3 tests in your browser. Submit checks all 92 tests on the server, hidden ones included.