CF1324F.Maximum White Subtree
普及/提高-
通过率:0%
AC君温馨提醒
该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。
题目描述
You are given a tree consisting of n vertices. A tree is a connected undirected graph with n−1 edges. Each vertex v of this tree has a color assigned to it ( av=1 if the vertex v is white and 0 if the vertex v is black).
You have to solve the following problem for each vertex v : 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 v ? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntw white vertices and cntb black vertices, you have to maximize cntw−cntb .
给你一棵由 n 个顶点组成的树。树是一个有 n−1 条边的连通无向图。这棵树的每个顶点 v 都有一种颜色(如果顶点 v 是白色,则颜色为 av=1 ;如果顶点 v 是黑色,则颜色为 0 )。
对于每个顶点 v 你都必须解决下面的问题:如果从给定的树中选择一棵包含顶点 v 的子树,那么白色顶点的数量和黑色顶点的数量之间的最大差是多少?树的子树是给定树的连接子图。更具体地说,如果选择包含 cntw 个白色顶点和 cntb 个黑色顶点的子树,则必须最大化 cntw−cntb 。
输入格式
The first line of the input contains one integer n ( 2≤n≤2⋅105 ) — the number of vertices in the tree.
The second line of the input contains n integers a1,a2,…,an ( 0≤ai≤1 ), where ai is the color of the i -th vertex.
Each of the next n−1 lines describes an edge of the tree. Edge i is denoted by two integers ui and vi , the labels of vertices it connects (1≤ui,vi≤n,ui=vi ).
It is guaranteed that the given edges form a tree.
输入
输入的第一行包含一个整数 n ( 2≤n≤2⋅105 )。( 2≤n≤2⋅105 ) - 树的顶点数。
第二行包含 n 个整数 a1,a2,…,an ( 0≤ai≤1 ),其中 ai 是第 i 个顶点的颜色。
接下来的每一行 n−1 都描述了树的一条边。边 i 由两个整数 ui 和 vi 表示,它连接的顶点的标签为 (1≤ui,vi≤n,ui=vi )。
可以保证给定的边构成一棵树。
输出格式
Print n integers res1,res2,…,resn , where resi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i .
输出
打印 n 个整数 res1,res2,…,resn ,其中 resi 是包含顶点 i 的某个子树上白色顶点和黑色顶点数量的最大可能差值。
输入输出样例
输入#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,3 and 4 are vertices 2,3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3 .
备注
第一个示例如图所示:
黑色顶点有粗体边框。
在第二个例子中,顶点 2,3 和 4 的最佳子树分别是顶点 2,3 和 4 。而顶点 1 的最佳子树是由顶点 1 和 3 组成的子树。