Restless Walkers

medium graphs bfs shortest-paths 1000 ms · 256 MB

Restless Walkers

Alice and Bob have agreed to meet somewhere in the city park, but neither of them can stand still for even a moment. The park has n clearings joined by m two-way trails, and walking any trail takes exactly one minute. Alice starts in clearing a and Bob in clearing b. Every minute, both of them must leave their current clearing and walk along some trail to a neighbouring clearing; nobody may wait in place. They can't call each other, but they planned their routes in advance, so they can coordinate perfectly. Passing each other in the middle of a trail doesn't count as meeting: they only meet if, at the end of some minute, they are standing in the same clearing.

Formally, find the smallest integer t ≥ 0 such that there are walks a = x_0, x_1, …, x_t and b = y_0, y_1, …, y_t where every pair of consecutive clearings x_{i-1}, x_i (and y_{i-1}, y_i) is joined by a trail, and x_t = y_t. Clearings and trails may be revisited any number of times. If a = b, the answer is 0.

Input

The first line contains four integers n, m, a, b (1 ≤ n ≤ 2·10^5, 0 ≤ m ≤ 2·10^5, 1 ≤ a, b ≤ n): the number of clearings, the number of trails, and the starting clearings of Alice and Bob.

Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v): a trail between clearings u and v. No two trails join the same pair of clearings.

Output

Print the minimum number of minutes after which Alice and Bob can stand in the same clearing, or -1 if they can never meet.

Notes

In the first example, the shortest route between them is a single trail, but crossing it in opposite directions doesn't count. One optimal plan is Alice walking 1 → 2 → 3 → 4 → 5 and Bob walking 2 → 3 → 4 → 6 → 5: they meet in clearing 5 after 4 minutes.

In the second example, whatever they do, after every minute exactly one of them stands in one of the clearings 1, 3, 5, so they never meet.

Example 1

Input

6 6 1 2
1 2
2 3
3 4
4 5
5 6
6 4

Output

4

Example 2

Input

5 5 2 5
1 2
2 3
3 4
4 1
4 5

Output

-1

Hints · reveal one at a time if you're stuck

Hint 1

Whoever arrives first can't wait for the other. But if Alice can stand in a clearing after d minutes, can she also stand there after d + 2 minutes? Which arrival times at a clearing are then possible?

Hint 2

Beyond a minimum, only the parity of the arrival time matters, and an odd cycle can let someone reach the same clearing at both parities. So for each clearing, what you need is the earliest arrival of each person for each parity, not just the shortest distance.

Hint 3

Make each state a pair (clearing, parity of minutes walked): every trail flips the parity. A breadth-first search over these states from each start gives the earliest arrivals you need.

report an issue Prefer your own editor? sooks prep 10 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.