Advertisement
pb_jiang

cf274b WA

Sep 27th, 2022
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <assert.h>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. #define dbg(...) logger(#__VA_ARGS__, __VA_ARGS__)
  5. template <typename... Args> void logger(string vars, Args &&...values)
  6. {
  7.     cerr << vars << " = ";
  8.     string delim = "";
  9.     (..., (cerr << delim << values, delim = ", "));
  10.     cerr << endl;
  11. }
  12.  
  13. template <class T> using mpq = priority_queue<T, vector<T>, greater<T>>;
  14. using ll = long long;
  15. using pii = pair<int, int>;
  16. using pll = pair<ll, ll>;
  17.  
  18. int n;
  19. vector<int> g[100003];
  20. int val[100003];
  21. int vis[100003];
  22.  
  23. pll dfs(int now)
  24. {
  25.     // op_cnt, op_offset
  26.     vis[now] = 1;
  27.     int out_cnt = 0;
  28.     ll op_acc = 0;
  29.     ll op_offset = 0;
  30.     for (auto out : g[now]) {
  31.         if (vis[out] == 0) {
  32.             auto op = dfs(out);
  33.             op_acc += op.first;
  34.             op_offset += op.second;
  35.             ++out_cnt;
  36.         }
  37.     }
  38.     if (out_cnt == 0) {
  39.         return {abs(val[now]), -val[now]};
  40.     }
  41.     ll new_offset = -(op_offset + val[now]);
  42.     ll new_op_acc = op_acc + abs(new_offset);
  43.     // return {op_acc + abs(val[now] + op_offset), -val[now] + op_offset};
  44.     return {new_op_acc, new_offset};
  45. }
  46.  
  47. int main(int argc, char **argv)
  48. {
  49.     scanf("%d", &n);
  50.     int a, b;
  51.     for (int i = 1; i < n; ++i) {
  52.         scanf("%d%d", &a, &b);
  53.         g[a].push_back(b);
  54.         g[b].push_back(a);
  55.     }
  56.     for (int i = 1; i <= n; ++i)
  57.         scanf("%d", val + i);
  58.     auto ret = dfs(1);
  59.     printf("%lld\n", ret.first);
  60.     return 0;
  61. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement