Random Walks in a Big City
Time limit5sMemory limit1024 MB
Given a connected road network, find the fewest minutes a student is guaranteed to reach home when random turns are adversarial, or -1 if they can wander forever.
- Level
Hard8 of 10
- Topics
- Graph, BFS, Game theory
- Solved
- No attempts yet
Statement
City N has crossroads and two-way roads connecting them. Every crossroad has at least two roads leaving it, and the road network connects every crossroad to every other crossroad. Any two crossroads are joined by at most one road.
A student has just left a nightlife venue near crossroad and wants to go home, which is near crossroad . Each minute, the following happens:
- The student chooses one of the roads leaving the current crossroad and walks along it.
- If the student is now at crossroad , they go home immediately and go to sleep.
- Otherwise, driven by an irresistible thirst for adventure, the student picks a road leaving the current crossroad at random and walks along it. The only restriction is that the student never picks the road they just used to arrive at this crossroad (the road used in step 1 of the current minute).
- If after this move the student is at crossroad , they go home.
Given the road network and the crossroads and , determine whether the student is guaranteed to get home in a finite number of steps. If so, find the minimum such that the student is guaranteed to be home within minutes, no matter which random choices they make in step 3 of each minute.
Input
The first line contains one integer (), the number of test cases. Each test case starts with a line containing four integers , , , and (, , ): the number of crossroads, the number of roads, the crossroad where the student starts, and the crossroad where the student wants to go. Each of the next lines contains two integers and (, ), the endpoints of the -th two-way road. It is guaranteed that every crossroad can reach every other crossroad using these roads, every crossroad has at least two roads, and no two roads join the same pair of crossroads. The sums of and of over all test cases each do not exceed .
Output
For each test case, print one integer. If the student can wander forever by making unlucky random choices, print . Otherwise, print the minimum number of minutes in which the student is guaranteed to get home when they make the best possible choice in step 1 of every minute.
Hint
In the first example, the student first walks to crossroad 3. Then they randomly choose the road to crossroad 2 or crossroad 4. If they choose crossroad 2, they get home immediately. Otherwise, they are at the crossroad next to home at the start of the next minute.
In the second example, the student can keep wandering between the pair of crossroads and the pair . Each time they walk toward crossroad 4 or 5, they may make an unlucky random choice and end up at crossroad 2 or 3.