Tree Shifting
You are given a rooted tree with nodes. There are
trips, the
-th starting at
and ending at
. The distance of a trip is the number of edges on the unique path between the endpoints.
For each node , you may perform the following operation:
- Remove the edge from
to its parent
. Add an edge from
to any node in the subtree rooted at
(could be
itself).
For each node , what is the minimum sum of trip distances you can get after performing this operation once on
?
If
is the root, output the original sum.
Input
The first line contains two integers and
(
) — the number of nodes in the tree and the number of trips.
The second line contains integers
, where
(
) is the parent of node
. Node
is the root of the tree.
The next lines each contain two integers
and
(
), representing the start and end points of the
-th trip.
Output
Output lines. The
-th line should contain the minimum possible sum of trip distances after performing the operation on node
. If node
is the root, output the original sum of trip distances.
Examples
Input 1
5 3
1 2 2 4
1 5
2 3
2 5
Output 1
6
4
6
4
6
Explanation 1
The tree structure is:
1
/
2
/ \
3 4
\
5
The original trip distances are
- Trip 1→5 has a distance of 3 (1→2→4→5)
- Trip 2→3 has a distance of 1 (2→3)
- Trip 2→5 has a distance of 2 (2→4→5)
so the total distance is 6.
For node 1 (the root), we just output the original distance of 6.
For node 2, we can remove the edge 1→2 and reconnect 1 to any node in the subtree of 2 (either 2, 3, 4 or 5). If we reconnect 1→5
- Trip 1→5 will have a distance of 1 (1→5)
- Trip 2→3 will have a distance of 1 (2→3)
- Trip 2→5 will have a distance of 2 (2→4→5)
so the total distance will be 4. This can be shown to be the minimum possible.
For node 3, after removing the edge 2→3 we must reconnect it so we output the original distance of 6.
For node 4, we can remove the edge 2→4 and reconnect 2 to any node in the subtree of 4 (either 4 or 5). If we reconnect 2→5
- Trip 1→5 will have a distance of 2 (1→2→5)
- Trip 2→3 will have a distance of 1 (2→3)
- Trip 2→5 will have a distance of 1 (2→5)
so the total distance will be 4. This can be shown to be the minimum possible.
For node 5, after removing the edge 4→5 we must reconnect it so we output the original distance of 6.
Input 2
4 2
1 1 2
1 4
3 2
Output 2
4
4
4
4
Explanation 2
The tree structure is:
1
/ \
2 3
\
4
The original trip distances are
- Trip 1→4 has a distance of 2 (1→2→4)
- Trip 3→2 has a distance of 2 (3→1→2)
so the total distance is 4.
No matter what node we try to perform this operation on, the total distance must be 4.
Of note, if we remove the edge 1→2 and add the edge 1→4
- Trip 1→4 will have a distance of 1 (1→4)
- Trip 3→2 will have a distance of 3 (3→1→4→2)
so the total distance will still be 4.
Input 3
10 6
1 1 2 2 3 3 4 4 5
1 10
1 10
1 10
3 8
3 7
7 8
Output 3
19
17
19
17
16
19
19
19
19
19
Comments