Advertisement
Josif_tepe

Untitled

Dec 2nd, 2023
609
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. typedef long long ll;
  4. const int maxn = 1e5 + 10;
  5. int n;
  6. int experience[maxn];
  7. vector<int> graph[maxn];
  8. ll dp[maxn][3];
  9.  
  10. void dfs(int node, int parent) {
  11.     ll sum = 0;
  12.     for(int neighbour : graph[node]) {
  13.         if(neighbour != parent) {
  14.             dfs(neighbour, node);
  15.             sum += dp[neighbour][0];
  16.         }
  17.     }
  18.     dp[node][1] = sum + experience[node];
  19.     dp[node][2] = sum - experience[node];
  20.    
  21.     for(int neighbour : graph[node]) {
  22.         if(neighbour != parent) {
  23.             dp[node][1] = max(dp[node][1], sum - dp[neighbour][0] + dp[neighbour][1]);
  24.             dp[node][2] = max(dp[node][2], sum - dp[neighbour][0] + dp[neighbour][2]);
  25.         }
  26.     }
  27.     dp[node][0] = max(dp[node][1] - experience[node], dp[node][2] + experience[node]);
  28. }
  29. int main()
  30. {
  31.     ios_base::sync_with_stdio(false);
  32.     cin >> n;
  33.    
  34.     for(int i = 0; i < n; i++) {
  35.         cin >> experience[i];
  36.     }
  37.     for(int i = 1; i < n; i++) {
  38.         int a, b;
  39.         cin >> a >> b;
  40.         a--; b--;
  41.    
  42.         graph[a].push_back(b);
  43.         graph[b].push_back(a);
  44.     }
  45.     dfs(0, -1);
  46.    
  47.     cout << dp[0][0] << endl;
  48.     return 0;
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement