Warping the Ward
A call bell is ringing in room , but you are in the hospital's break room. You need to get to your patient, stat!
The hospital has rooms, numbered
to
, joined by
one-way hallways. Every room except room
has exactly one hallway leading into it, and every room can be reached from room
. You start in room
and need to get to room
. More formally, it is a unidirectional tree rooted at node
.
We'll say that room is
hallways deeper than room
if the route from
to
passes through exactly
hallways.
To move between rooms, the hospital is trialling an inter-dimensional remote. If you are standing in some room , you can pick an integer
with
and teleport to any room
hallways deeper than
. More formally, you can pick an integer
with
and teleport to any node in
's subtree that is
hallways deeper than
.
However, teleporting is very loud! Each time you use the remote, you must first warn every room that is hallways deeper than
, including the one you are traveling to. Warnings take
second per room.
Moving optimally, what is the minimum total time required to get from room to room
?
Input
The first line contains three integers ,
, and
(
,
,
), the number of rooms in the hospital, the room you need to travel to, and the greatest depth you can travel with a single use of the remote.
The second line contains integers
(
), where
is the room that the hallway leading into room
.
It is guaranteed that .
Output
Output a single integer, the minimum total time to reach room , in seconds.
Example
Input 1
12 12 2
1 1 2 2 2 2 2 3 7 7 11
Output 1
5
The optimal route is:
- Teleport from room
to room
, which is
hallway deeper. There are
rooms exactly
hallway deeper than room
, so you spend
seconds warning them.
- Teleport from room
to room
, which is
hallways deeper. There are
rooms exactly
hallways deeper than room
, so you spend
seconds warning them.
- Teleport from room
to room
, which is
hallway deeper. There is only
room exactly
hallway deeper than room
, so you spend
second warning it.
This gives a total of seconds.

Input 2
17 14 2
1 6 1 1 2 4 7 14 17 17 17 17 10 1 11 6
Output 2
6

Input 3
20 20 9
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Output 3
3
Comments