Cod sursa(job #2600072)

Utilizator retrogradLucian Bicsi retrograd Data 11 aprilie 2020 22:20:58
Problema Heavy Path Decomposition Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.33 kb
#include <bits/stdc++.h>
 
using namespace std;
 
 
struct LinkCut {
  struct Node {
    int p = 0, c[2] = {0, 0}, pp = 0;
    bool flip = 0;
    int val = 0, dp = 0;
  };
  vector<Node> T;
 
  LinkCut(int n) : T(n + 1) {}
 
  // SPLAY TREE OPERATIONS START
  int dir(int x, int y) { return T[x].c[1] == y; }
 
  void set(int x, int d, int y) {
    if (x) { 
      T[x].c[d] = y; pull(x);
    }
    if (y) T[y].p = x;
  }
 
  void pull(int x) {
    if (!x) return;
    int &l = T[x].c[0], &r = T[x].c[1];
    T[x].dp = max({T[x].val, T[l].dp, T[r].dp});
  }
 
  void push(int x) {
    if (!x || !T[x].flip) return;
    int &l = T[x].c[0], &r = T[x].c[1];
    swap(l, r); T[l].flip ^= 1; T[r].flip ^= 1;
    T[x].flip = 0;
  }
 
  void rotate(int x, int d) { 
    int y = T[x].p, z = T[y].p, w = T[x].c[d];
    swap(T[x].pp, T[y].pp);
    set(y, !d, w);
    set(x, d, y);
    set(z, dir(z, y), x);
  }
 
  void splay(int x) { 
    for (push(x); T[x].p;) {
      int y = T[x].p, z = T[y].p;
      push(z); push(y); push(x);
      int dx = dir(y, x), dy = dir(z, y);
      if (!z) {
        rotate(x, !dx); 
      }
      else if (dx == dy) 
        rotate(y, !dx), rotate(x, !dx); 
      else
        rotate(x, dy), rotate(x, dx);
    }
  }
 
  // SPLAY TREE OPERATIONS END
 
  void Link(int u, int v) { 
    MakeRoot(v);
    T[v].pp = u;
  }
 
  /// Move u to root of represented tree.
  void MakeRoot(int u) {
    Access(u);
    int l = T[u].c[0];
    T[l].flip ^= 1;
    swap(T[l].p, T[l].pp);
    push(T[u].c[0]);
    set(u, 0, 0);
  }
 
  void Access(int _u) {
    for (int v = 0, u = _u; u; u = T[v = u].pp) {
      splay(u); splay(v);
      int r = T[u].c[1];
      T[v].pp = 0;
      swap(T[r].p, T[r].pp);
      set(u, 1, v);
    }
    splay(_u);
  }
 
  void Update(int u, int val) {
    splay(u);
    T[u].val = val;
    pull(u);
  }
 
  int Query(int u, int v) {
    MakeRoot(u);
    Access(v);
    return T[v].dp;
  }
};
 
int main() {
  // Test();
  ifstream cin("heavypath.in");
  ofstream cout("heavypath.out");
 
  int n, m; cin >> n >> m;
  LinkCut lc(n);
  for (int i = 1; i <= n; ++i) {
    cin >> lc.T[i].val;
  }
 
  for (int i = 1; i < n; ++i) {
    int a, b; cin >> a >> b;
    lc.Link(a, b);
  }
 
  for (int i = 0; i < m; ++i) {
    int t, a, b; cin >> t >> a >> b;
    if (t == 0) lc.Update(a, b);
    else cout << lc.Query(a, b) << '\n';
  }
  return 0;
}