Cod sursa(job #2807991)

Utilizator victorzarzuZarzu Victor victorzarzu Data 24 noiembrie 2021 13:48:18
Problema Heavy Path Decomposition Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.56 kb
#include <bits/stdc++.h>
#define n_max 100000

using namespace std;
ifstream f("heavypath.in");
ofstream g("heavypath.out");
int n, m, pos;
int v[n_max + 5], heavy[n_max + 5], size[n_max + 5], seq[n_max + 5], t[n_max + 5], arb[4 * n_max + 5], level[n_max + 5], parent[n_max + 5], position[n_max + 5];
vector<int> graf[n_max + 5];

void read()
{
  f>>n>>m;
  for(int i = 1;i <= n;++i)
    f>>v[i];
  int x, y;
  for(int i = 1;i < n;++i)
    f>>x>>y, graf[x].push_back(y), graf[y].push_back(x);
}

void dfs(int node, int par) 
{
  size[node] = 1;
  parent[node] = par;
  level[node] = level[par] + 1;

  int maximum = 0;
  for(auto it : graf[node])
    if(it != par)
      {
        dfs(it, node);
        size[node] += size[it];

        if(maximum < size[it])
          heavy[node] = it, maximum = size[it];
      }
}

void decomposition(int node, int superior)
{
  seq[node] = superior;
  position[node] = ++pos;

  if(heavy[node])
    decomposition(heavy[node], superior);
  
  for(auto it : graf[node])
    if(it != parent[node] && it != heavy[node])
      decomposition(it, it);
}

void update(int node, int left, int right, int position, int value)
{
  if(position < left || position > right)
    return;

  if(left == right)
  {
    arb[node] = value;
    return;
  }

  int mid = (left + right) >> 1;
  update(2 * node, left, mid, position, value);
  update(2 * node + 1, mid + 1, right, position, value);

  arb[node] = max(arb[node * 2], arb[node * 2 + 1]);
}

int query(int node, int left, int right, int a, int b)
{
  if(left > right || right < a || left > b)
    return 0;

  if(a <= left && right <= b)
    return arb[node];
  
  int mid = (left + right) >> 1;
  return max(query(2 * node, left, mid, a, b), query(2 * node + 1, mid + 1, right, a, b)); 
}

int query_all(int x, int y)
{
  int result = 0;
  while(seq[x] != seq[y])
  {
    if(level[seq[x]] < level[seq[y]])
      swap(x, y);

    result = max(result, query(1, 1, n, position[seq[x]], position[x]));
    x = parent[seq[x]];
  }

  if(level[x] < level[y])
    swap(x, y);
  result = max(result, query(1, 1, n, position[y], position[x]));

  return result;
}

void solve()
{
  dfs(1, 0);
  decomposition(1, 1);
  for(int i = 1;i <= n;++i)
    update(1, 1, n, position[i], v[i]);    
  
  int x, y, z;
  for(int i = 1;i <= m;++i)
    {
      f>>x>>y>>z;
      if(x)
        g<<query_all(y, z)<<'\n';
      else
        update(1, 1, n, position[y], z);
        
    }
} 

int main()
{
  read();
  solve();
  return 0;
}