Advertisement
Josif_tepe

Untitled

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