Cod sursa(job #3195908)

Utilizator PatruMihaiPatru Mihai PatruMihai Data 22 ianuarie 2024 08:58:41
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 15007;
const int MMAX = 30007;

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

vector<numar> v(MMAX);
vector<pair<int, int>> l[NMAX];
vector<int> tata(NMAX, -1);
vector<int> tata2(NMAX);
vector<int> lvl(NMAX);
vector<int> c(NMAX);

bool cmp(numar a, numar b)
{
    return a.c < b.c;
}

int root(int x)
{
    while (tata[x] > 0)
    {
        x = tata[x];
    }
    return x;
}

void dfs(int nod, int dad)
{
    tata2[nod] = dad;
    lvl[nod] = lvl[dad] + 1;
    for (int i = 0; i < l[nod].size(); i++)
    {
        int vec = l[nod][i].first;
        int cost = l[nod][i].second;
        if (vec != dad)
        {
            c[vec] = cost;
            dfs(vec, nod);
        }
    }
}

int main()
{
    int n, m, k;
    fin >> n >> m >> k;
    for (int i = 1; i <= m; i++)
    {
        fin >> v[i].x >> v[i].y >> v[i].c;
    }

    sort(v.begin(), v.end(), cmp);

    int i = 1, nr = 0;
    while (nr < n - 1)
    {
        int rx = root(v[i].x);
        int ry = root(v[i].y);
        if (rx != ry)
        {
            nr++;
            l[rx].emplace_back(ry, v[i].c);
            l[ry].emplace_back(rx, v[i].c);
            if (tata[rx] < tata[ry])
            {
                tata[rx] += tata[ry];
                tata[ry] = rx;
            }
            else
            {
                tata[ry] += tata[rx];
                tata[rx] = ry;
            }
        }
        i++;
    }

    dfs(1, 0);

    while (k--)
    {
        int x, y;
        fin >> x >> y;

        int maxim = INT_MIN;

        while (lvl[x] > lvl[y])
        {
            maxim = max(maxim, c[x]);
            x = tata2[x];
        }
        while (lvl[y] > lvl[x])
        {
            maxim = max(maxim, c[y]);
            y = tata2[y];
        }
        while (x != y)
        {
            maxim = max(maxim, max(c[x], c[y]));
            x = tata2[x];
            y = tata2[y];
        }
        fout << maxim << "\n";
    }

    return 0;
}