This page is still under construction.

Parts of this page are still being built. What you see may change.

Conquer the World

Time limit8sMemory limit1024 MB

Summary
Armies sit on the nodes of a weighted tree; move them along edges to satisfy each node's demand while minimizing total transport cost.
Level

Hard8 of 10

Topics
Tree, DFS, Greedy
Solved
No attempts yet

Problem

Bwahahahahaha!!! Your nemesis, the dashingly handsome spy Waco Powers, has at last fallen to your secret volcano base's deathtraps (or so you assume, being a little too busy to witness it firsthand). At long last, you are all set to CONQUER THE WORLD!

Nothing will stand in your way! Well, nothing except a minor problem of logistics. Your evil armies have announced that they will not continue carving their relentless path of destruction across the puny nations of the world without being paid. And unfortunately you are running low on cash. A volcano lair has many wonderful qualities, but "reasonably affordable" is not one of them. You have had to pull funds from the travel budget to pay your ungrateful underlings. Now you are not sure how you will actually get your armies into position to CONQUER THE WORLD.

You have a map of the nations of the world and all your available transport routes between them. Each route connects two nations and has a fixed cost per army that uses it. The routes are laid out such that there is exactly one way to travel between any two nations. You know the current position of each of your armies and how many you will need to place permanently in each nation in order to subjugate it. How can you move the armies into place as cheaply as possible so you can CONQUER THE WORLD?

Input

The first line contains an integer nn (1≤n≤2500001 \le n \le 250000), the number of nations. Then follow n−1n-1 lines, each containing three integers uu, vv, and cc (1≤u,v≤n1 \le u, v \le n, 1≤c≤1061 \le c \le 10^6), meaning that a bidirectional route connects nations uu and vv and costs cc per army that uses it.

Then follow nn more lines. The ii-th of them contains two non-negative integers xix_i and yiy_i, meaning that nation ii currently holds xix_i armies and that the final arrangement must leave at least yiy_i armies there. The total number of armies, the sum of the xix_i values, is at least the sum of the yiy_i values and at most 10610^6.

Output

Print the minimum cost of moving the armies so that nation ii ends up with at least yiy_i armies for every ii.

Examples3

  1. Example 1

    Input
    3
    1 2 5
    3 1 5
    2 1
    5 0
    1 3
    
    Expected output
    15
    
  2. Example 2

    Input
    6
    1 2 2
    1 3 5
    1 4 1
    2 5 5
    2 6 1
    0 0
    1 0
    2 1
    2 1
    0 1
    0 1
    
    Expected output
    9
    
  3. Example 3

    Input
    1
    5 3
    
    Expected output
    0