Cod sursa(job #2937595)

Utilizator DooMeDCristian Alexutan DooMeD Data 10 noiembrie 2022 18:04:19
Problema Heavy Path Decomposition Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <bits/stdc++.h>
using namespace std;
const int nmax = 1e5;

vector<vector<int>> dx(nmax+5);
int n, q, val[nmax+5], dim[nmax+5], par[nmax+5], niv[nmax+5];

int in[nmax+5], timer = 0, nxt[nmax+5];
int v[nmax+5], aint[2*nmax+5];

void dfs_dim(int node) {
    dim[node] = 1;
    for(auto &i : dx[node]) {
        dx[i].erase(find(dx[i].begin(), dx[i].end(), node));
        niv[i] = niv[node] + 1;
        par[i] = node;
        dfs_dim(i);
        dim[node] += dim[i];
        if(dim[i] > dim[dx[node][0]]) swap(i, dx[node][0]);
    }
}

void dfs_hld(int node) {
    in[node] = timer++;
    for(auto i : dx[node]) {
        nxt[i] = (i == dx[node][0] ? nxt[node] : i);
        dfs_hld(i);
    }
}

void build() {
    for(int i=0; i<n; i++) aint[i+n] = v[i];
    for(int i=n-1; i>=1; i--) aint[i] = max(aint[i*2], aint[i*2+1]);
}

void upd(int pos, int w) {
    for(aint[pos+=n]=w; pos>1; pos/=2) aint[pos/2] = max(aint[pos], aint[pos^1]);
}

int query(int st, int dr) {
    int temp = 0;
    for(st+=n, dr+=n; st<dr; st/=2, dr/=2) {
        if(st&1) temp = max(temp, aint[st++]);
        if(dr&1) temp = max(temp, aint[--dr]);
    }
    return temp;
}

int main() {
    ifstream f("heavypath.in");
    ofstream g("heavypath.out");

    f >> n >> q;
    for(int i=1; i<=n; i++) f >> val[i];
    for(int i=1; i<=n-1; i++) {
        int x, y; f >> x >> y;
        dx[x].emplace_back(y);
        dx[y].emplace_back(x);
    }
    nxt[1] = 1;
    dfs_dim(1);
    dfs_hld(1);
    for(int i=1; i<=n; i++) v[in[i]] = val[i];
    build();
    for(int i=1; i<=q; i++) {
        int type, x, y; f >> type >> x >> y;
        if(type == 0) upd(in[x], y);
        else {
            int ans = 0;
            while(nxt[x] != nxt[y]) {
                if(niv[nxt[x]] < niv[nxt[y]]) swap(x, y);
                ans = max(ans, query(in[nxt[x]], in[x]+1));
                x = par[nxt[x]];
            }
            if(in[x] > in[y]) swap(x, y);
            ans = max(ans, query(in[x], in[y]+1));
            g << ans << "\n";
        }
    }
    return 0;
}