This page is still under construction.

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

Great Cow Gathering

Interview

Time limit1sMemory limit128 MB

Summary
Pick a node of a weighted tree with node weights as the gathering point, and minimize the sum of cow count times distance to that node.
Level

Medium6 of 10

Topics
Tree, DFS, Dynamic programming, Prefix sum
Solved
No attempts yet

Problem

Bessie is planning the annual Great Cow Gathering and wants to choose the most convenient barn to host it.

Every cow lives in one of NN barns, numbered 11 through NN. The barns are connected by N−1N-1 roads so that you can travel between any two barns. Road ii connects barns AiA_i and BiB_i and has length LiL_i; the barns therefore form a tree. Barn ii is home to CiC_i cows.

The gathering may be held in any single barn. If it is held in barn XX, its inconvenience is the total distance every cow must travel to reach XX: a barn holding CiC_i cows at distance dd from XX contributes Ci⋅dC_i \cdot d. For example, if 33 cows live in a barn 2020 units away from XX, they add 3×20=603 \times 20 = 60 to the inconvenience.

Choose the barn that minimizes the total inconvenience, and report that minimum inconvenience.

Constraints

  • 1≤N≤100,0001 \le N \le 100{,}000
  • 1≤Ai,Bi≤N1 \le A_i, B_i \le N
  • 1≤Li≤1,0001 \le L_i \le 1{,}000
  • 0≤Ci≤1,0000 \le C_i \le 1{,}000

Input

  • Line 11: a single integer NN.
  • Lines 22 to N+1N+1: line i+1i+1 contains a single integer CiC_i, the number of cows in barn ii.
  • Lines N+2N+2 to 2N2N: each of these N−1N-1 lines contains three integers AiA_i, BiB_i, and LiL_i, describing a road of length LiL_i between barns AiA_i and BiB_i.

Output

  • A single line containing the minimum possible inconvenience.

Examples2

  1. Example 1

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

    Input
    2
    1
    1
    1 2 5
    
    Expected output
    5