Cod sursa(job #3358001)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 22:48:56
Problema Heavy Path Decomposition Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.05 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

const int N = 1e5 + 5;

int n, m, v[N], tata[N], h[N], sz[N], heavy[N], pos[N], aib[N];
vector<int> g[N], lant[N];

void dfs(int x) {
    sz[x] = 1;
    int maxsz = 0;
    for (int y : g[x]) {
        if (y != tata[x]) {
            tata[y] = x;
            h[y] = h[x] + 1;
            dfs(y);
            sz[x] += sz[y];
            if (sz[y] > maxsz) {
                maxsz = sz[y];
                heavy[x] = y;
            }
        }
    }
}

void hpd(int x) {
    int i = 1;
    for (int y : g[x]) {
        if (y != tata[x] && y == heavy[x]) {
            lant[i] = lant[i - 1];
            lant[i].push_back(x);
            pos[x] = lant[i].size() - 1;
            hpd(y);
            i++;
        }
    }
    for (int y : g[x]) {
        if (y != tata[x] && y != heavy[x]) {
            lant[i] = {x};
            pos[x] = 0;
            hpd(y);
            i++;
        }
    }
}

void update(int x, int y) {
    int p = pos[x];
    for (int i = p; i >= 0; i -= i & -i) {
        aib[i] = max(aib[i], y);
    }
}

int query(int x, int y) {
    int p = pos[x];
    int sol = 0;
    for (int i = p; i <= lant[x].size(); i += i & -i) {
        sol = max(sol, aib[i]);
    }
    return sol;
}

int main() {
    ifstream cin("heavypath.in");
    ofstream cout("heavypath.out");

    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> v[i];
    }
    for (int i = 1; i < n; i++) {
        int x, y;
        cin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    dfs(1);
    hpd(1);
    for (int i = 1; i <= n; i++) {
        update(i, v[i]);
    }
    while (m--) {
        int t, x, y;
        cin >> t >> x >> y;
        if (t == 0) {
            update(x, y);
        } else {
            int sol = 0;
            while (x != y) {
                if (h[x] < h[y]) {
                    swap(x, y);
                }
                sol = max(sol, query(x, y));
                x = tata[heavy[x]];
            }
            cout << sol << '\n';
        }
    }

    return 0;
}