Cod sursa(job #2924206)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 27 septembrie 2022 09:15:54
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.63 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

struct str{
    int x, c;
};

struct mch{
    int x, y, c;
};

const int max_size = 15e3 + 1, rmax = 15;

int lvl[max_size], lg[max_size], f[max_size];
str t[rmax][max_size];
vector <str> mc[max_size];
vector <mch> apm;

void dfs (int nod, int par, int cost)
{
  //  out << par << " " << nod << '\n';
    t[0][nod].x = par;
    t[0][nod].c = cost;
    lvl[nod] = lvl[par] + 1;
    for (auto f : mc[nod])
    {
        if (f.x != par)
        {
            dfs(f.x, nod, f.c);
        }
    }
}

str anc (int x, int ord)
{
    str ans = {x, 0};
    int e = 0;
    while (ord > 0)
    {
        if (ord % 2 == 1)
        {
            ans.x = t[e][x].x;
            ans.c = max(t[e][x].c, ans.c);
            x = t[e][x].x;
        }
        e++;
        ord /= 2;
    }
    return ans;
}

int lca (int x, str ry)
{
    int mx1 = 0, mx2 = ry.c, y = ry.x;
    int e = lg[lvl[x]];
    while (e >= 0)
    {
        if (t[e][x].x != t[e][y].x)
        {
            mx1 = max(t[e][x].c, mx1);
            x = t[e][x].x;
            mx2 = max(t[e][y].c, mx2);
            y = t[e][y].x;
        }
        e--;
    }
    return max(max(mx1, mx2), max(t[0][x].c, t[0][y].c));
}

void uniune (int x, int y)
{
    f[x] = y;
}

bool cmp (mch x, mch y)
{
    return x.c <= y.c;
}

int rad (int x)
{
    if (x == f[x])
    {
        return x;
    }
    return rad(f[x]);
}

int main ()
{
    int n, m, q;
    in >> n >> m >> q;
    for (int i = 1; i <= n; i++)
    {
        f[i] = i;
    }
    for (int i = 1; i <= m; i++)
    {
        mch x;
        in >> x.x >> x.y >> x.c;
        apm.push_back(x);
    }
    sort(apm.begin(), apm.end(), cmp);
    for (auto f : apm)
    {
        if (rad(f.x) != rad(f.y))
        {
            mc[f.x].push_back({f.y, f.c});
            mc[f.y].push_back({f.x, f.c});
            uniune(rad(f.x), rad(f.y));
        }
    }
    dfs(1, 0, 0);
    for (int e = 1; e < rmax; e++)
    {
        for (int i = 1; i <= n; i++)
        {
            t[e][i].x = t[e - 1][t[e - 1][i].x].x;
            t[e][i].c = max(t[e - 1][i].c, t[e - 1][t[e - 1][i].x].c);
        }
    }
    for (int i = 2; i <= n; i++)
    {
        lg[i] = lg[i /2] + 1;
    }
    while (q--)
    {
        int x, y;
        in >> x >> y;
        if (lvl[x] > lvl[y])
        {
            swap(x, y);
        }
        str ry = anc(y, lvl[y] - lvl[x]);
        if (ry.x == x)
        {
            out << ry.c << '\n';
        }
        else
        {
            out << lca(x, ry) << '\n';
        }
    }
    in.close();
    out.close();
    return 0;
}