Whitewater rafting and canoeing are fun activities, especially on hot summer days. Splashing water cools you off in the rapids, then the current carries you to another part of the river. There are many different rivers to choose from, each with its own set of rapids. Which river is the most fun, and which section of that river?
From each rapid , the current flows to some unique other rapid
, except when
is the last rapid on a
given river. It is possible for one river to flow into another; in this case, the current flows from two or
more different rapids
to the same downriver rapid
. Since water always flows downhill, it is not
possible for the current to start at some rapid
and eventually return to the original rapid
.
To make fun precise, we will assign each rapid a score
. You can choose to start your
trip at some rapid, then flow with the current to successive rapids until you either get tired and decide to
stop, or until you reach the last rapid of a river. The overall score of a trip is the sum of the scores of the
rapids that you passed through. You are at some starting rapid and wondering where you should stop to
maximize the overall score of your trip.
Sadly, as summer turns to fall, water levels get lower and some sections of the river are no longer navigable.
In other words, where previously the current flowed from rapid to rapid
, it now no longer does. It is
still possible to start a trip at rapid
, but any trip that goes to rapid
must stop there; it can no longer
continue to rapid
.
Input Specification
The first line contains two integers - and
, with
.
This is followed by lines that describe the initial state of the rivers. The
'th such line contains two
integers
and
. If
is
, then rapid
is at the end of a river.
Otherwise,
indicates the next downriver rapid that rapid
flows into.
is the fun score of the
'th rapid.
This is followed by lines that describe changes to the water levels over time and queries. Each of these
lines contains two integers
,
. If
is
, then this line indicates that rapid
now becomes the end of a river (i.e. it no longer flows to any other rapid). In this case, it is guaranteed
that rapid x was not already the end of a river. If
is
, then this query asks you to output the maximum
amount of fun that can be obtained by starting your trip at rapid
.
Output Specification
Output one line for each query with , indicating the maximum fun you can have for that query.
Output should be in the same order as the queries appear in the input.
Sample Input 1
2 3
0 5
1 5
2 2
1 2
2 2
Sample Output 1
10
5
Sample Input 2
5 5
0 5
1 -1
2 5
0 3
2 0
2 3
1 2
2 3
2 4
2 2
Sample Output 2
9
5
3
-1
Comments