Advertisement
ThegeekKnight16

Tree Weights

Oct 19th, 2023
819
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long
  4. const int MAXN = 1e5 + 10;
  5. const int MAXK = 21;
  6. array<array<int, MAXK>, MAXN> dp;
  7. array<vector<int>, MAXN> grafo;
  8. array<int, MAXN> prof;
  9.  
  10. void dfs(int v, int p)
  11. {
  12.     prof[v] = prof[p]+1;
  13.     dp[v][0] = p;
  14.    
  15.     for (int k = 1; k < MAXK; k++) dp[v][k] = dp[dp[v][k-1]][k-1];
  16.    
  17.     for (auto viz : grafo[v])
  18.     {
  19.         if (viz == p) continue;
  20.         dfs(viz, v);
  21.     }
  22. }
  23.  
  24. int lca(int x, int y)
  25. {
  26.     if (prof[x] < prof[y]) swap(x, y);
  27.     int D = prof[x] - prof[y];
  28.     for (int k = 0; k < MAXK; k++)
  29.         if (D & (1 << k)) x = dp[x][k];
  30.        
  31.     if (x == y) return x;
  32.    
  33.     for (int k = MAXK-1; k >= 0; k--)
  34.         if (dp[x][k] != dp[y][k])
  35.             x = dp[x][k], y = dp[y][k];
  36.    
  37.     return dp[x][0];
  38. }
  39.  
  40. int32_t main()
  41. {
  42.     ios_base::sync_with_stdio(false);
  43.     cin.tie(NULL);
  44.     int N;
  45.     cin >> N;
  46.     vector<pair<int, int>> edges(N);
  47.     for (auto &[x, y] : edges)
  48.     {
  49.         cin >> x >> y;
  50.         grafo[x].push_back(y);
  51.         grafo[y].push_back(x);
  52.     }
  53.     dfs(1, 1);
  54.     vector<tuple<int, int, int, int>> queries(N);
  55.     for (int i = 1; i < N; i++)
  56.     {
  57.         int X;
  58.         cin >> X;
  59.         queries[i-1] = make_tuple(i, i+1, lca(i, i+1), X);
  60.     }
  61.        
  62.    
  63.     vector<int> x(N+1); x[1] = 0;
  64.     for (int m = 2; m <= (int)1e12; m *= 2)
  65.     {
  66.         for (auto [a, b, l, X] : queries)
  67.         {
  68.             x[b] = (X % m) + ((2 * x[l]) % m) - (x[a] % m);
  69.             x[b] = ((x[b] % m) + m) % m;
  70.         }
  71.     }
  72.    
  73.     vector<int> resp;
  74.     for (auto [X, Y] : edges)
  75.     {
  76.         if (prof[X] < prof[Y]) swap(X, Y);
  77.         resp.push_back(x[X] - x[Y]);
  78.         if (resp.back() <= 0) {cout << -1 << '\n'; return 0;}
  79.     }
  80.    
  81.     for (auto X : resp) cout << X << '\n';
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement