In NTHU, there are numerous Oloo stations interconnected by roads forming a tree structure. Each road has its passage time.
To ensure easy access for everyone to borrow Oloo, the operating company need to redistribute Oloo among stations during night so that each station has an equal number of Oloos.
You're given a tree consisting of $N$ nodes and $N-1$ edges, representing the map of NTHU campus. Each node is an Oloo station number from $0$ to $N - 1$, and the number of Oloo in Oloo station $i$ is denoted as $a_i$. The edges are represented by (u, v, w)
, where edge (u, v)
connects node $u$ and node $v$, and the time required to traverse this edge is denoted by $w$.
The total cost of redistributing Oloo is calculated as the sum of distances each Oloo is moved, considering the passage time of each road. The objective is to minimize this cost. Write a program to help calculate the minimum cost.
The first line contains an integer $T$, which is the number of testcases. For each testcase:
$N$
$a_1 \quad a_2 \quad \dots \quad a_N$
$u_1 \quad v_1 \quad w_1$
$u_2 \quad v_2 \quad w_2$
$\vdots$
$u_{N-1} \quad v_{N-1} \quad w_{N-1}$
For each testcase, output its minimum cost. If it's impossible, print -1
as the answer.