Kingdom of Magic
InterviewTime limit2sMemory limit128 MB
On a graph of up to 100 cities, two people who must always sit on adjacent distinct vertices move to a target adjacent pair, minimizing total single or paired moves.
- Level
Medium7 of 10
- Topics
- Graph, BFS, Shortest path, Implementation
- Solved
- No attempts yet
Problem
The Kingdom of Magic has a network of bidirectional magic portals connecting its cities. Each portal directly connects a pair of cities and lets people travel quickly between them. Two cities joined by a portal are called neighboring.
Prince Albert and Princess Betty live in two neighboring cities and are deeply in love, yet they have never met and refuse to ever be in the same city at the same time. Therefore, wherever they go, they must always stay in a pair of neighboring, distinct cities (two different cities directly connected by a portal).
To move, they use the portals. In a single step they may either:
- move just one of them through one portal (the other stays put), or
- move both of them at the same time, each through a different portal.
They may never move through the same portal at the same time. After every step they must again occupy a pair of neighboring, distinct cities.
The cost of a step is the number of people who move: moving one person costs move, and moving both at once costs moves.
Given the portal network together with Albert's and Betty's starting cities and their destination cities, compute the minimal total number of moves needed to bring them from their starting pair of neighboring cities to their target pair of neighboring cities. It is guaranteed that this is possible.
Input
The first line contains six integers , , , , , . Here () is the number of cities (numbered from to ) and () is the number of portals. Albert and Betty start in the neighboring cities and (, ) and want to reach the neighboring cities and (, ), with or .
Each of the next lines contains two integers and (, ), the two cities connected by that portal. At most one portal connects any pair of cities.
Output
Print a single integer: the minimal total number of moves needed to bring Albert and Betty from to .