Cod sursa(job #2392338)

Utilizator ezioconnorVlad - Gabriel Iftimescu ezioconnor Data 29 martie 2019 21:44:34
Problema Heavy Path Decomposition Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>

using namespace std;

ifstream in("heavypath.in");
ofstream out("heavypath.out");

int n, m;
long long v[100001];
int father[100001], depth[100001], ancestor[100001];
vector <int> Muchii[100001];

inline void DFS(int nod, int prev, int nivel)
{
    int vecin;
    depth[nod] = nivel;
    ancestor[nod] = prev;
    for (int i = 0; i < Muchii[nod].size(); ++i)
    {
        vecin = Muchii[nod][i];
        if (vecin != prev)
            DFS(vecin, nod, nivel + 1);
    }
}

inline void citire()
{
    int x, y;
    in >> n >> m;
    for (int i = 1; i <= n; ++i)
        in >> v[i];
    for (int i = 1; i < n; ++i)
    {
        in >> x >> y;
        Muchii[x].push_back(y);
        Muchii[y].push_back(x);
    }
}

inline long long lca(int x, int y)
{
    long long MAX = 0;
    while (ancestor[x] != ancestor[y])
    {
        MAX = max(MAX, v[x]);
        MAX = max(MAX, v[y]);
        if (depth[x] > depth[y])
            x = ancestor[x];
        else
            y = ancestor[y];
    }
    while (x != y)
    {
        MAX = max(MAX, v[x]);
        MAX = max(MAX, v[y]);
        if (depth[x] > depth[y])
            x = ancestor[x];
        else
            y = ancestor[y];
    }
    if (x == y)
        MAX = max(MAX, v[x]);
    return MAX;
}

int main()
{
    int c, x, y;
    citire();
    DFS(1, 0, 0);
    for (int q = 1; q <= m; ++q)
    {
        in >> c >> x >> y;
        if (c == 0)
            v[x] = y;
        else
            out << lca(x, y) << '\n';
    }
    return 0;
}