Cod sursa(job #1311361)

Utilizator japjappedulapPotra Vlad japjappedulap Data 8 ianuarie 2015 00:20:06
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.24 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

#define PII pair<int, int>
#define Edge pair<int,PII>
#define x first
#define y second

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

int N, M, Qr;
vector <PII> APM[15001];
vector <Edge> E;

int Depth[15001];
int T[15001], R[15001], ApmSize;
bool B[15001];

void Read();
void Make_APM();
void DFS(int X);
void Solve();
int Root(int k);
void Unite(int a, int b);
int FindLCA(int A, int B);

int main()
{
    Read();
    Make_APM();
    Depth[1] = 1;
    DFS(1);
    Solve();
}

void Read()
{
    is >> N >> M >> Qr;
    for (int a, b, c; M; --M)
        is >> a >> b >> c, E.push_back({c, {a, b}});
};

void Make_APM()
{
    for (int i = 1; i <= N; ++i)
        T[i] = i, R[i] = 1;
    sort(E.begin(), E.end());
    int Rx, Ry;
    for (const auto& m : E)
    {
        Rx = Root(m.y.x);
        Ry = Root(m.y.y);
        if (Rx != Ry)
        {
            Unite(Rx, Ry);
            ApmSize++;
            APM[m.y.x].push_back({m.y.y, m.x});
        }
        if (ApmSize >= N-1)
            break;
    }
    for (int i = 1; i <= N; ++i)
        T[i] = 0, R[i] = 0;
};

void Solve()
{
    for (int X, Y; Qr; --Qr)
    {
        is >> X >> Y;
        os << FindLCA(X, Y) << '\n';
    }
};

int FindLCA(int A, int B)
{
    int val = 0;
    while (Depth[A] > Depth[B])
    {
        val = max(val, R[A]);
        A = T[A];
    }
    while (Depth[A] < Depth[B])
    {
        val = max(val, R[B]);
        B = T[B];
    }
    while (A != B)
    {
        val = max(val, max(R[A], R[B]));
        A = T[A], B = T[B];
    }
    return val;
};

int Root(int k)
{
    int r = k;
    while (T[r] != r) r = T[r];
    for (int s; T[k] != k; s = T[k], T[k] = r, k = s);
    return r;
};

void Unite(int a, int b)
{
    if (R[a] > R[b])
        T[b] = a;
    else
    {
        T[a] = b;
        if (R[a] == R[b])
            R[b]++;
    }
};

void DFS(int X)
{
    B[X] = 1;
    for (const auto& Y : APM[X])
        if (B[Y.x] == 0)
        {
            T[Y.x] = X;
            Depth[Y.x] = Depth[X]+1;
            R[Y.x] = Y.y;
            DFS(Y.x);
        }
};