Cod sursa(job #3290858)

Utilizator Radu_MocanasuMocanasu Radu Radu_Mocanasu Data 1 aprilie 2025 14:46:38
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.32 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nrb = 14;

vector < vector < pair <int, int> > > G(15005);
vector < pair < int, pair <int, int> > > edges;

int t[15005];
int h[15005];

int findr(int x){
    int r = x;
    while(r != t[r]) r = t[r];
    while(x != r){
        int y = t[x];
        t[x] = r;
        x = y;
    }
    return r;
}

int dsu(int x, int y){
    int rx = findr(x), ry = findr(y);
    if(rx == ry) return 0;
    if(h[rx] > h[ry]) t[ry] = rx;
    else{
        if(h[rx] == h[ry]) h[ry]++;
        t[rx] = ry;
    }
    return 1;
}

void kruskal(){
    for(auto x : edges){
        if(dsu(x.second.first, x.second.second)){
            G[x.second.first].push_back({x.first, x.second.second});
            G[x.second.second].push_back({x.first, x.second.first});
        }
    }
}

int t2[15005][nrb];
int dp[15005][nrb];

int h2[15005];

void dfs(int nod, int tt){
    t2[nod][0] = tt;
    h2[nod] = h2[tt] + 1;
    for(int i = 1; i < nrb; i++){
        t2[nod][i] = t2[t2[nod][i - 1]][i - 1];
        dp[nod][i] = max(dp[nod][i - 1], dp[t2[nod][i - 1]][i - 1]);
    }
    for(auto x : G[nod]){
        if(x.second == tt) continue;
        dp[x.second][0] = x.first;
        dfs(x.second, nod);
    }
}

int lca(int x, int y){
    if(h2[x] < h2[y]) swap(x, y);
    int d = h2[x] - h2[y], rez = 0;
    for(int i = nrb - 1; i >= 0; i--){
        if((1 << i) & d){
            rez = max(rez, dp[x][i]);
            x = t2[x][i];
        }
    }
    if(x == y) return rez;
    for(int i = nrb - 1; i >= 0; i--){
        if(t2[x][i] != t2[y][i]){
            rez = max(rez, dp[x][i]);
            rez = max(rez, dp[y][i]);
            x = t2[x][i];
            y = t2[y][i];
        }
    }
    rez = max(rez, dp[x][0]);
    rez = max(rez, dp[y][0]);
    return rez;
}

int main()
{
    int n,i,q,m,x,y,c;
    fin >> n >> m >> q;
    while(m--){
        fin >> x >> y >> c;
        edges.push_back({c, {x, y}});
    }
    for(i = 1; i <= n; i++) t[i] = i;
    sort(edges.begin(), edges.end());
    kruskal();
    for(i = 1; i <= n; i++){
        if(!t2[i][0]) dfs(i, 0);
    }
    while(q--){
        fin >> x >> y;
        fout << lca(x, y) << "\n";
    }
    return 0;
}