fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. #define fi first
  5. #define se second
  6. #define int long long
  7. typedef pair<int,int> pii;
  8. const int MAXN = 2e5 +5;
  9.  
  10. int ans2 =0, total =0;
  11. vector <int> adj[MAXN];
  12. vector <int> a(MAXN), sum(MAXN), ans(MAXN);
  13. //bool vis[MAXN];
  14.  
  15. void dfs(int x, int p, int h){
  16. ans[1] += h*a[x];
  17. sum[x] = a[x];
  18.  
  19. for (auto i : adj[x]){
  20. if (i != p) {
  21. dfs(i, x, h+1);
  22. sum[x] += sum[i];
  23. }
  24. }
  25. }
  26.  
  27. void dfs2(int x, int p){
  28. if ( x != 1){
  29. ans[x] = ans[p] - sum[x] + total- sum[x];
  30. }
  31.  
  32. ans2 = max(ans2, ans[x]);
  33.  
  34. for (auto i : adj[x]){
  35. if(i != p) {
  36. dfs2(i, x);
  37. }
  38. }
  39. }
  40. signed main(){
  41. ios_base::sync_with_stdio(0); cin.tie(0);
  42. int n;
  43. cin >> n;
  44.  
  45.  
  46. for (int i =1; i <= n; i++){
  47. cin >> a[i];
  48. total += a[i];
  49. }
  50. for (int i =1; i <= n-1; i++){
  51. int x, y;
  52. cin >> x >> y;
  53. adj[x].push_back(y);
  54. adj[y].push_back(x);
  55. }
  56.  
  57.  
  58. dfs(1, 0, 0);
  59. dfs2(1, 0);
  60. cout << ans2;
  61. }
Success #stdin #stdout 0.01s 12508KB
stdin
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
stdout
121