Chairs
View as PDFIan is in his FIT2004 class, and wants to ask the TA for help to solve a -dimensional dynamic programming problem.
The classroom can be modelled as an rectangle, with the bottom left located at
, and the top right located at
. Note that coordinates along the edge of the rectangle are inside the classroom.
Unfortunately there are chairs blocking his way, located at distinct coordinates.
Ian, from any coordinate , can move to any adjacent coordinate inside the classroom:
When moving, Ian has a set of specific interactions:
Step from the ground onto the top of the chair, which requires
unit of energy.
Step from a chair onto the ground, which requires
unit of energy.
Step from a chair onto a chair, which does not require energy.
Step from the ground onto the ground, which does not require energy.
All interactions take second of time.
Ian is currently at position , and the TA is located at position
.
Since Ian values his time and energy, he would like to know the minimum energy he must use to reach the TA in at most seconds.
Input
The first line contains .
The next line contains .
The next lines each contain
, the coordinates of the
-th chair.
Output
Output a single number, the minimum energy that Ian must use to move from to
in at most
seconds, or
if Ian cannot reach the TA in time.
Constraints
are distinct
Example 1
Input
3 3
1 1 3 3 3 5
1 2
2 2
3 2
Output
2
Explanation
Ian can take the path .
Moving from requires stepping from the ground onto a chair, which uses
energy.
Moving from requires stepping from a chair onto the ground, which uses
energy.
In total, Ian uses energy, and reaches the TA within
seconds.
It can be shown that this path minimises Ian's energy usage.
Example 2
Input
3 3
1 1 1 3 2 6
1 2
2 2
Output
0
Example 3
Input
3 3
1 1 3 3 7 4
1 2
1 3
2 1
2 2
2 3
3 1
3 2
Output
2
Comments