CF1324F.Maximum White Subtree

普及/提高-

通过率:0%

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

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 .
给你一棵由 nn 个顶点组成的树。树是一个有 n1n-1 条边的连通无向图。这棵树的每个顶点 vv 都有一种颜色(如果顶点 vv 是白色,则颜色为 av=1a_v = 1 ;如果顶点 vv 是黑色,则颜色为 00 )。

对于每个顶点 vv 你都必须解决下面的问题:如果从给定的树中选择一棵包含顶点 vv 的子树,那么白色顶点的数量和黑色顶点的数量之间的最大差是多少?树的子树是给定树的连接子图。更具体地说,如果选择包含 cntwcnt_w 个白色顶点和 cntbcnt_b 个黑色顶点的子树,则必须最大化 cntwcntbcnt_w - cnt_b

输入格式

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.
输入

输入的第一行包含一个整数 nn2n21052 \le n \le 2 \cdot 10^5 )。( 2n21052 \le n \le 2 \cdot 10^5 ) - 树的顶点数。

第二行包含 nn 个整数 a1,a2,,ana_1, a_2, \dots, a_n ( 0ai10 \le a_i \le 1 ),其中 aia_i 是第 ii 个顶点的颜色。

接下来的每一行 n1n-1 都描述了树的一条边。边 ii 由两个整数 uiu_iviv_i 表示,它连接的顶点的标签为 (1ui,vin,uivi(1 \le u_i, v_i \le n, u_i \ne v_i )。

可以保证给定的边构成一棵树。

输出格式

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 .
输出

打印 nn 个整数 res1,res2,,resnres_1, res_2, \dots, res_n ,其中 resires_i 是包含顶点 ii 的某个子树上白色顶点和黑色顶点数量的最大可能差值。

输入输出样例

  • 输入#1

    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

    输出#1

    2 2 2 2 2 1 1 0 2
  • 输入#2

    4
    0 0 1 0
    1 2
    1 3
    1 4

    输出#2

    0 -1 1 -1

说明/提示

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 .
备注

第一个示例如图所示:

黑色顶点有粗体边框。

在第二个例子中,顶点 2,32, 344 的最佳子树分别是顶点 2,32, 344 。而顶点 11 的最佳子树是由顶点 1133 组成的子树。

首页