CF1324F.Maximum White Subtree

普及+/提高

通过率:0%

时间限制:2.00s

内存限制:256MB

AC君温馨提醒

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

题目描述

You are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n-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 cntw−cntbcnt_w - cnt_b.

给你一棵包含 nn 个顶点的树。树是一种具有 n−1n-1 条边的连通无向图。该树的每个顶点 vv 均被赋予一种颜色(若顶点 vv 为白色,则 av=1a_v = 1;若为黑色,则 av=0a_v = 0)。

你需要对每个顶点 vv 求解如下问题:在所有包含顶点 vv 的子树中,白色顶点数与黑色顶点数之差(即 cntw−cntbcnt_w - cnt_b)的最大值是多少?此处“子树”指原树的一个连通子图。更准确地说,若所选子树包含 cntwcnt_w 个白色顶点和 cntbcnt_b 个黑色顶点,则目标是最大化 cntw−cntbcnt_w - cnt_b。

输入格式

The first line of the input contains one integer nn (2≤n≤2⋅1052 \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 (0≤ai≤10 \le a_i \le 1), where aia_i is the color of the ii-th vertex.

Each of the next n−1n-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 (1≤ui,vi≤n,ui≠vi(1 \le u_i, v_i \le n, u_i \ne v_i).

It is guaranteed that the given edges form a tree.

输入的第一行包含一个整数 nn(2≤n≤2⋅1052 \le n \le 2 \cdot 10^5)——树中顶点的数量。

输入的第二行包含 nn 个整数 a1,a2,…,ana_1, a_2, \dots, a_n(0≤ai≤10 \le a_i \le 1),其中 aia_i 表示第 ii 个顶点的颜色。

接下来的 n−1n-1 行每行描述树中的一条边。第 ii 条边由两个整数 uiu_i 和 viv_i 表示,即该边所连接的两个顶点的编号(1≤ui,vi≤n1 \le u_i, v_i \le n,且 ui≠viu_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.

第一个示例如下所示:

黑色顶点具有粗边框。

在第二个示例中,顶点 22、33 和 44 的最优子树分别为仅包含顶点 22、仅包含顶点 33、仅包含顶点 44 的子树;而顶点 11 的最优子树是由顶点 11 和 33 构成的子树。

输入解题思路,AI测评打分。不知道怎么写?

首页