Cod sursa(job #2046974)

Utilizator mlc_oficialBoris Barca mlc_oficial Data 24 octombrie 2017 13:01:59
Problema Heavy Path Decomposition Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.3 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

static const int kMagic = 256;

void dfs(const vector< vector<int> >& G, int node, vector<int>& super_parent, vector<int>& parent, vector<int>& depth) {
    if (depth[node] % kMagic == 0)
        super_parent[node] = node;

    for (auto&& son : G[node])
        if (parent[node] != son) {
            super_parent[son] = super_parent[node];
            parent[son] = node;
            depth[son] = depth[node] + 1;
            dfs(G, son, super_parent, parent, depth);
        }
}

int main() {
#ifdef LOCAL
    ifstream cin("a.in");
#else
    ifstream cin("heavypath.in");
    ofstream cout("heavypath.out");
#endif

    int N, Q; cin >> N >> Q;
    vector<int> V(N);
    for (int i = 0; i < N; ++i)
        cin >> V[i];
    
    vector<vector<int> > G(N);
    for (int i = 1; i < N; ++i) {
        int x, y; cin >> x >> y; x--; y--;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    vector<int> super_parent(N), parent(N, -1);
    vector<int> depth(N);
    dfs(G, 0, super_parent, parent, depth);

    vector<int> super_value(N);
    vector< vector<int> > super_descendants(N);
    for (int i = 0; i < N; ++i) {
        super_value[super_parent[i]] = max(super_value[super_parent[i]], V[i]);
        super_descendants[super_parent[i]].push_back(i);
    }

    while (Q--> 0) {
        int type; cin >> type;
        if (type == 0) {
            int node, value; cin >> node >> value; node--;
            V[node] = value;
            
            const int sparent = super_parent[node];
            super_value[sparent] = 0;
            for (auto&& x : super_descendants[sparent])
                if (V[x] > super_value[sparent])
                    super_value[sparent] = V[x];
        } else {
            int x, y; cin >> x >> y; x--; y--;
            int ans = 0;
            while (super_parent[x] != super_parent[y]) {
                if (depth[x] < depth[y])
                    swap(x, y);
                ans = max(ans, super_value[super_parent[x]]);
                x = parent[super_parent[x]];
            }

            while (x != y) {
                if (depth[x] < depth[y])
                    swap(x, y);
                ans = max(ans, V[x]);
                x = parent[x];
            }
            cout << ans << '\n';
        }
    }
}