Cod sursa(job #3332539)

Utilizator CarenaMironov Cezar Luca Carena Data 7 ianuarie 2026 13:35:14
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.27 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX=15e3+5, LG=13;
int n, m, k, depth[NMAX]={-1}, lift[LG+5][NMAX], maxp[LG+5][NMAX];

struct edge
{
    int u, v, c;
    friend bool operator<(const edge a, const edge b)
    {
        return a.c<b.c;
    }
    int other(int x)
    {
        return x^u^v;
    }
}e[2*NMAX];
vector<edge> adj[NMAX];

struct DSU
{
    int p[NMAX], sz[NMAX];
    
    void init()
    {
        for(int i=1;i<=n;i++)
        {
            p[i]=i;
            sz[i]=1;
        }
    }
    
    int find(int u)
    {
        return ((u==p[u])?u:p[u]=find(p[u]));
    }
    
    bool merge(int u, int v)
    {
        u=find(u); v=find(v);
        if(u==v)
            return 0;
        if(sz[u]<sz[v])
            swap(u, v);
        p[v]=u; sz[u]+=sz[v];
        return 1;
    }
}ds;

void APM()
{
    ds.init();
    sort(e+1, e+m+1);
    for(int i=1;i<=m;i++)
        if(ds.merge(e[i].u, e[i].v))
        {
            adj[e[i].u].push_back(e[i]);
            adj[e[i].v].push_back(e[i]);
        }
}

void DFS(int u)
{
    for(auto ev:adj[u])
        if(ev.other(u)!=lift[0][u])
        {
            int v=ev.other(u);
            depth[v]=depth[u]+1;
            lift[0][v]=u; maxp[0][v]=ev.c;
            for(int b=1;b<=LG;b++)
            {
                lift[b][v]=lift[b-1][lift[b-1][v]];
                maxp[b][v]=max(maxp[b-1][v], maxp[b-1][lift[b-1][v]]);
            }
            DFS(v);
        }
}

int LCA(int u, int v)
{
    int ans=0, pas;
    if(depth[u]>depth[v])
        swap(u, v);
    
    pas=LG;
    while(pas>=0)
    {
        if(depth[lift[pas][v]]>=depth[u])
        {
            ans=max(ans, maxp[pas][v]);
            v=lift[pas][v];
        }
        pas--;
    }
    
    if(u==v)
        return ans;
    
    pas=LG;
    while(pas>=0)
    {
        if(lift[pas][u]!=lift[pas][v])
        {
            ans=max(ans, max(maxp[pas][u], maxp[pas][v]));
            u=lift[pas][u]; v=lift[pas][v];
        }
        pas--;
    }
    return max(ans, max(maxp[0][u], maxp[0][v]));
}

int main()
{
    in>>n>>m>>k;
    for(int i=1;i<=m;i++)
        in>>e[i].u>>e[i].v>>e[i].c;
    APM();
    DFS(1);
    while(k--)
    {
        int x, y; in>>x>>y;
        out<<LCA(x, y)<<'\n';
    }
    return 0;
}