Rentib

słowacki powraca na 100

Feb 7th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #ifndef _zad_h_
  2. #define _zad_h_
  3. #include<vector>
  4. #include<tuple>
  5. using namespace std;
  6.  
  7. int tree[1 << 20], M = 1, nr = -1;
  8. vector<int> pre, pos;
  9. int up[100007][20];
  10.  
  11. vector<pair<int, int>> G[100007];
  12. void DFS(int a, int fat, int d){
  13.   pre[a] = ++nr;
  14.   tree[pre[a] + M] = d;
  15.   up[a][0] = fat;
  16.   for(int i = 1;i < 20;i++)
  17.     up[a][i] = up[up[a][i - 1]][i - 1];
  18.   for(auto i : G[a])
  19.     if(i.first != fat)
  20.       DFS(i.first, a, d + i.second);
  21.   pos[a] = nr;
  22. }
  23. bool ancestor(int a, int b){
  24.   return pre[a] <= pre[b] && pos[a] >= pos[b];
  25. }
  26. void init(vector<tuple<int, int, int>> e){
  27.   int n = e.size() + 1, m = e.size();
  28.   pre.resize(n + 7); pos.resize(n + 7);
  29.   while(M <= n)
  30.     M *= 2;
  31.   for(int i = 0, v, u, w;i < m;i++){
  32.     tie(v, u, w) = e[i];
  33.     G[v].emplace_back(u, w);
  34.     G[u].emplace_back(v, w);
  35.   }
  36.   DFS(1, 1, 0);
  37. }
  38. int LCA(int a, int b){
  39.   if(ancestor(a, b))
  40.     return a;
  41.   if(ancestor(b, a))
  42.     return b;
  43.   for(int i = 19;i >= 0;i--)
  44.     if(!ancestor(up[a][i], b))
  45.       a = up[a][i];
  46.   return up[a][0];
  47. }
  48. int spacer(int v, int d = 0){
  49.   v = pre[v] + M;
  50.   while(v){
  51.     d += tree[v];
  52.     v /= 2;
  53.   }
  54.   return d;
  55. }
  56. int distance(int a, int b){
  57.   return spacer(a) + spacer(b) - 2 * spacer(LCA(a, b));
  58. }
  59. void change(int a, int b, int c){
  60.   int v = ancestor(a, b) ? b : a;
  61.   c -= abs(spacer(a) - spacer(b));
  62.   int p = pre[v] + M, k = pos[v] + M;
  63.   while(p <= k && p > 0 && k > 0){
  64.     if(p % 2 == 1) tree[p++] += c;
  65.     if(k % 2 == 0) tree[k--] += c;
  66.     p /= 2;
  67.     k /= 2;
  68.   }
  69. }
  70.  
  71. #endif
  72. /*
  73. JESTEM Z SIEBIE DUMNY
  74. */
Advertisement
Add Comment
Please, Sign In to add comment