Your brother, who recently broke his leg, needs to take the subway from your house to the pharmacy to get his prescription of pain medication.
This subway system is made of
Changing lines requires going up or down a floor in a subway station. Unfortunately, due to your brother's
broken leg, he needs the assistance of an escalator to change lines. Not every line changing station is built
with escalators, and some line changing stations only have escalators going in one direction (i.e. for example, it
may be possible to go from Line
As a regular subway user, you have recorded the availability of escalators on the subway system. For example,
you may have recorded that there is an escalator allowing a line change from somewhere on Line
Please find the least number of line changes your brother must make to get to the pharmacy. (Don't worry about travel times or anything like that, just minimize the number of line changes based on the available escalators to get from the house to the pharmacy). It is guaranteed that your brother is able to make it to the pharmacy.
Note: It is not required (and not possible given the information provided) to visualize the actual layout of the subway system to solve the problem. You only need to know which line changes are possible to make.
Input Specification
The first line of input will contain
The next
Output Specification
Output one integer, the least number of line changes your brother needs to do to get to the pharmacy.
Constraints
- For 3 of 10 marks,
and - For the remaining 7 marks, there are no additional constraints
Sample Input
8 1 6 9
1 2
2 3
1 4
4 7
7 8
3 2
8 6
3 5
6 5
Sample Output
4
Explanation for Sample Output
Your brother starts on Line 1. In order to reach the pharmacy on Line 6, he can take this path:
Line 1 -> Line 4 -> Line 7 -> Line 8 -> Line 6
This path requires four transfers. It is easy to see that this path requires the least number of transfers.
Comments