CF1324F.Maximum White Subtree

传统题 时间 2000 ms 内存 256 MiB 9 尝试 3 已通过 1 标签

Maximum White Subtree

You are given a tree consisting of nn vertices. A tree is a connected undirected graph with n1n-1 edges. Each vertex vv of this tree has a color assigned to it (av=1a_v = 1 if the vertex vv is white and 00 if the vertex vv is black).

You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcnt_w white vertices and cntbcnt_b black vertices, you have to maximize cntwcntbcnt_w - cnt_b.

Input

The first line of the input contains one integer nn (2n21052 \le n \le 2 \cdot 10^5) — the number of vertices in the tree.

The second line of the input contains nn integers a1,a2,,ana_1, a_2, \dots, a_n (0ai10 \le a_i \le 1), where aia_i is the color of the ii-th vertex.

Each of the next n1n-1 lines describes an edge of the tree. Edge ii is denoted by two integers uiu_i and viv_i, the labels of vertices it connects (1ui,vin,uivi(1 \le u_i, v_i \le n, u_i \ne v_i).

It is guaranteed that the given edges form a tree.

Output

Print nn integers res1,res2,,resnres_1, res_2, \dots, res_n, where resires_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.

Note

The first example is shown below:

The black vertices have bold borders.

In the second example, the best subtree for vertices 2,32, 3 and 44 are vertices 2,32, 3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.

Samples

9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
2 2 2 2 2 1 1 0 2 
4
0 0 1 0
1 2
1 3
1 4
0 -1 1 -1 

在线编程 IDE

建议全屏模式获得最佳体验