Under construction

Still being built. Things may change

KK Nations

Time limit1sMemory limit1024 MB

Summary
Partition a tree of cities into connected groups, each with total power at most U, minimizing the sum of squared gaps (U minus group power).
Level

Medium6 of 10

Topics
Dynamic programming, Tree
Solved
No attempts yet

Combat Power Split

You are playing shake!, a war simulation game popular around the world. The game has NN cities numbered from 1 to NN, and each city has a combat power. There are also N−1N-1 roads that connect two different cities in both directions, and you can travel between any two cities along the roads.

You plan to found several nations and run a war simulation. Each nation must contain at least one city, and each city must belong to exactly one nation. Any two cities in the same nation must be connected by roads without passing through a city of another nation.

Splitting combat power evenly matters. A nation that is too powerful wins wars too easily, and the game loses its appeal. The combat power of a nation is the sum of the combat powers of all cities in it. You set a combat power cap UU. No nation may exceed UU, and if kk (1≤k≤N1 \leq k \leq N) nations have combat powers w1,w2,…,wkw_1, w_2, \dots, w_k, the balanced split is the one that minimizes ∑i=1k(U−wi)2\sum_{i=1}^{k} (U-w_i)^2. Split the combat power of the nations this way.

Input

The first line contains the number of cities NN. (1≤N≤10 0001 \leq N \leq 10\,000)

The next NN lines each contain the combat power cic_i of city ii. (1≤ci≤1001 \leq c_i \leq 100)

The next N−1N-1 lines describe the roads. Each line contains the two city numbers that the road connects, separated by a space.

The last line contains the combat power cap UU. (max⁡1≤i≤Nci≤U≤100\max_{1 \leq i \leq N} c_i \leq U \leq 100)

Output

Print the minimum value of ∑i=1k(U−wi)2\sum_{i=1}^{k} (U-w_i)^2.

Examples3

  1. Example 1

    Input
    10
    3
    2
    1
    1
    6
    3
    2
    1
    2
    2
    2 9
    10 4
    5 1
    3 7
    6 9
    7 2
    9 1
    2 10
    8 2
    10
    
    Expected output
    21
    
  2. Example 2

    Input
    4
    2
    2
    2
    2
    1 3
    3 2
    4 3
    3
    
    Expected output
    4
    
  3. Example 3

    Input
    4
    2
    2
    2
    2
    1 3
    3 2
    4 3
    8
    
    Expected output
    0