Travels in Reality#900

Travels in Reality

1 second
64 megabytes
Hard

Every time a significant event occurs in the world, our reality splits into several different branches according to the various outcomes of that event. After this, not only does our original reality exist, but also all those that branched off at different times, each representing a different possibility.

One day, an archmage decided to make the world a better place. Such a monumental task was beyond the power of just one archmage, so he resolved to seek out himself in other realities and undertake the task together. Theoretical research revealed that, apart from the reality in which he currently resides, there are N - 1 other realities. For convenience, these realities are numbered from to , with his own reality having number . He must visit realities numbered , , , K + 1.

Each reality, except for one Initial reality, separated from some other reality at a certain moment. The Initial reality has always existed (its number can be any; it is assumed to appear at time ). Research has shown that the reality numbered branched off from the reality numbered P_i at time T_i. From each reality numbered , the archmage can move:

In other words, only transitions of the type i \rightarrow P_i are possible. For every such transition in any direction, the archmage expends T_i - T_{P_i} (strictly positive) units of energy.

Find the minimum energy needed for the archmage, starting in reality , to visit all realities numbered from to K + 1 (in any order), and then return to . Each reality may be visited any number of times.

Input

The first line contains two integers and (0 \leq K < N \leq 100\,000): the number of realities and the number to visit. This is followed by pairs of integers, where the th pair is P_i and T_i (1 \leq P_i \leq N, 0 \leq T_i \leq 10^6; for the Initial reality P_i = T_i = 0).

It is guaranteed that a branched reality appeared strictly later than the one it branched from (T_i > T_{P_i}), and that the archmage can reach any of the realities if necessary.

Output

Output a single integer — the minimal possible energy needed for the archmage's journey.

Examples

Example 1

Loading
Loading