#P3642. [APIO2016] 烟花表演

[APIO2016] 烟花表演

Description

A fireworks show is one of the most eye-catching festival activities. In the show, all fireworks must explode at the same time. For safety, the fireworks are placed away from the switch and connected to the switch by fuses. The fuses form a tree, and the fireworks are the leaves, as shown in the figure. A spark starts at the switch and travels along the fuses. Whenever the spark reaches a junction, it splits and continues burning along all incident fuses. The burning speed of every fuse is a fixed constant. The figure shows the layout connecting six fireworks {E1,E2,,E6}\{E_1, E_2, \dots, E_6\} and the length of each fuse. It also shows the explosion time of each firework when the spark is ignited at time 00 at the switch.

Hyunmin designed the fuse layout for the fireworks show. Unfortunately, in his design, the fireworks do not necessarily explode simultaneously. We want to adjust some fuse lengths so that all fireworks explode at the same time. For example, to make all fireworks in the figure explode at time 1313, we can adjust the fuse lengths as shown on the left below. Similarly, to make all fireworks explode at time 1414, we can adjust the lengths as shown on the right.

The cost of modifying a fuse is the absolute difference between its new length and its original length. For example, changing the top layout to the layout on the left below has a total cost of 66, while changing it to the layout on the right has a total cost of 55.

Fuse lengths may be reduced to 00 without changing the connectivity.

Given a fuse layout, write a program to adjust the fuse lengths so that all fireworks explode at the same time, while minimizing the total cost.

Input Format

All input values are positive integers. Let NN be the number of junctions, and MM be the number of fireworks. Junctions are numbered from 11 to NN, where junction 11 is the switch. Fireworks are numbered from N+1N + 1 to N+MN + M.

The first line contains N,MN, M. Each of the next N+M1N + M - 1 lines describes one edge. For every node vv with 2vN+M2 \leq v \leq N + M, the line for vv gives two integers Pv,CvP_v, C_v, where 1Pv<v1 \leq P_v < v specifies the junction to which node vv is connected, and CvC_v is the length of the connecting fuse (1Cv1091 \leq C_v \leq 10^9). Except for the switch, every junction is connected to more than 11 fuse, and each firework is connected to exactly 11 fuse.

Output Format

Output the minimum total cost to adjust the fuse lengths so that all fireworks explode simultaneously.

4 6
1 5
2 5
2 8
3 3
3 2
3 3
2 9
4 4
4 3
5

Hint

Constraints

  • Subtask 1 (7 points): N=1N = 1, 1M1001 \leq M \leq 100.
  • Subtask 2 (19 points): 1N+M3001 \leq N + M \leq 300, and the distance from the switch to any firework is at most 300300.
  • Subtask 3 (29 points): 1N+M50001 \leq N + M \leq 5000.
  • Subtask 4 (45 points): 1N+M3000001 \leq N + M \leq 300000.

Translated by ChatGPT 5