当前位置: 代码迷 >> 综合 >> A - Maximum White Subtree
  详细解决方案

A - Maximum White Subtree

热度:16   发布时间:2024-02-25 05:12:22.0

链接:https://vjudge.net/contest/399019#problem/A

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=1av=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 cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw?cntbcntw?cntb.

Input

The first line of the input contains one integer nn (2≤n≤2?1052≤n≤2?105) — the number of vertices in the tree.

The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai 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 uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).

It is guaranteed that the given edges form a tree.

Output

Print nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.

Examples

Input

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

Output

2 2 2 2 2 1 1 0 2 

Input

4
0 0 1 0
1 2
1 3
1 4

Output

0 -1 1 -1 

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.

代码:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll maxn=2e5+7;
const ll mod=1e9+7;
ll n,k,s;
ll a[maxn],vis[maxn],ans[maxn];
ll dp[maxn];
vector<ll>q[maxn];
void dfs(int i)
{vis[i]=1;for(int j=0;j<q[i].size();j++){int u=q[i][j];if(vis[u]==0){dfs(u);if(a[u]>0)a[i]+=a[u];}}
}
void ddfs(int i,ll x)
{vis[i]=1;ans[i]=a[i]+x;for(int j=0;j<q[i].size();j++){int u=q[i][j];if(vis[u]==0){ddfs(u,max(0ll,ans[i]-max(0ll,a[u])));}}
}
int main()
{cin>>n;for(int i=1;i<=n;i++){cin>>a[i];if(a[i]==0)a[i]=-1;vis[i]=0;ans[i]=0;}for(int i=1;i<=n-1;i++){int u,v;cin>>u>>v;q[u].push_back(v);q[v].push_back(u);}dfs(1);for(int i=1;i<=n;i++){vis[i]=0;}ddfs(1,0);for(int i=1;i<=n;i++){cout<<ans[i]<<" ";}return 0;
}

 

  相关解决方案