Problem 624
Bus Routes
Hard · 30 pts · Graph, Breadth-First Search, Hash Table
Problem
Each bus route is a list of stops that the bus visits in a loop forever. You start at stop SOURCE (not on any bus) and want to reach stop TARGET, riding buses only. Find the minimum number of buses you must take, or -1 if it is impossible; if SOURCE equals TARGET the answer is 0. Run a breadth-first search where each level boards new buses: from every reached stop, board every unused route through it and reach all of that route's stops.
Input
The first line contains R, SOURCE and TARGET. Each of the next R lines starts with the number of stops of a route, followed by its stops.
Output
Print the minimum number of buses, or -1.
Constraints
1 <= R <= 500; total number of stops over all routes <= 100000; 0 <= stop < 10^6; stops within a route are distinct
Example input
2 1 6 3 1 2 7 3 3 6 7
Example output
2
Explanation
With routes 1 2 7 and 3 6 7, going from 1 to 6: take the first bus from 1 to 7, then change to the second bus at 7 and ride to 6. That is 2 buses.