1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| #include "iostream" #include "algorithm" #include "cstring" #include "cstdio" #include "cmath" #include "vector" #include "map" #include "set" #include "queue" using namespace std; #define MAXN 50006
#define rep(i, a, b) for (int i = (a), i##end = (b); i <= i##end; ++i) #define per(i, a, b) for (int i = (a), i##end = (b); i >= i##end; --i) #define pii pair<int,int> #define fi first #define se second #define mp make_pair #define pb push_back #define eb emplace_back #define vi vector<int> #define all(x) (x).begin() , (x).end() #define mem( a ) memset( a , 0 , sizeof a ) typedef long long ll; typedef double db; const int P = 998244353; int n , m , q; int A[MAXN];
vi G[MAXN];
int dp[MAXN] , as[MAXN] , re[MAXN]; void dfs( int u , int f ) { dp[u] = A[u]; for( int v : G[u] ) if( v != f ) { dfs( v , u ); if( dp[v] > dp[u] ) as[u] += max( dp[u] , 0 ) , dp[u] = -1; else as[u] += max( dp[v] , 0 ) , dp[u] -= max( dp[v] , 0 ); as[u] += as[v]; } }
int pd[MAXN] , er[MAXN] , dep[MAXN] , sd; void dfs$( int u , int f ) { if( u != 1 ) { re[u] = as[u]; int lef = dp[u] + 1; if( dp[u] < 0 ) ++ re[u]; re[u] += min( lef , pd[f] ); re[u] += er[f]; re[u] = re[u] * 2 + sd - dep[u]; } pd[u] = dp[u] + 1; vi ps( G[u].size() + 1 ) , pse( G[u].size() + 1 ); per( i , G[u].size() - 1 , 0 ) if( G[u][i] != f ) { ps[i] = ps[i + 1] + max( dp[G[u][i]] , 0 ) , pse[i] = pse[i + 1] + as[G[u][i]]; } else ps[i] = ps[i + 1] , pse[i] = pse[i + 1]; int pr = 0 , pe = 0; for( int i = 0 ; i < G[u].size() ; ++ i ) if( G[u][i] != f ) { int v = G[u][i]; int lef = pr + ps[i + 1] + pd[f]; pd[u] = max( A[u] + ( u != 1 ) - lef , 0 ); er[u] = pe + pse[i + 1] + er[f] + min( lef , A[u] + ( u != 1 ) ); dep[v] = dep[u] + 1; dfs$( v , u ); pr += max( dp[v] , 0 ) , pe += as[v]; } }
void solve() { cin >> n; rep( i , 1 , n ) scanf("%d",A + i); rep( i , 2 , n ) { int u , v; scanf("%d%d",&u,&v); ++ u , ++ v; G[u].pb( v ) , G[v].pb( u ); } rep( i , 1 , n ) A[i] -= G[i].size() , sd += G[i].size(); dfs( 1 , 1 ); re[1] = as[1] * 2 + sd; dfs$( 1 , 0 ); rep( i , 1 , n ) printf("%d\n",re[i]); }
signed main() {
solve(); }
|