Cod sursa(job #3042291)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 5 aprilie 2023 13:51:18
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.1 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <tuple>

using namespace std;
ifstream cin("radiatie.in");
ofstream cout("radiatie.out");
using pi = pair<int,int>;
const int N = 15009, LG = 20, Inf = 0x3f3f3f3f;

int n,m,k,a,b,c;
vector<vector<pi>> G;
int f[N][LG],dp[N][LG],dep[N];

struct muchie {int a,b,c;
muchie(int x,int y,int z) : a(x),b(y),c(z){}};

vector<muchie> muchii;
int t[N];

int find(int x)
{
    return (t[x] == 0) ? x : (t[x] = find(t[x]));
}
void unite(int a,int b,int c)
{
    int ra = find(a),rb = find(b);
    if(ra == rb)return;
    t[ra] = rb;
    G[a].push_back({b,c});
    G[b].push_back({a,c});
}

void get_tree()
{
    G = vector<vector<pi>>(n+1);

    while(m--)
    {
        cin>>a>>b>>c;
        muchii.emplace_back(a,b,c);
    }

    sort(muchii.begin(),muchii.end(),[](muchie a,muchie b) {return a.c < b.c;});

    for(auto aux : muchii)
    {
        int a = aux.a, b = aux.b, c = aux.c;
        unite(aux.a,aux.b,aux.c);
    }
}

void Dfs(int x,int p)
{
    for(int i = 1; i < LG; ++i)
    {
        f[x][i] = f[f[x][i-1]][i-1];
        dp[x][i] = max(dp[x][i-1],dp[f[x][i-1]][i-1]);
    }

    for(auto aux : G[x])
    {
        int y = aux.first,
        w = aux.second;

        if(y == p)continue;

        f[y][0] = x;
        dp[y][0] = w;
        dep[y] = dep[x] + 1;
        Dfs(y,x);
    }
}

int get_sol(int a,int b)
{
    if(a == b)return 0;

    if(dep[a] < dep[b])
        swap(a,b);

    int sol = -Inf;

    for(int i = LG - 1; i >= 0; --i)
        if(dep[f[a][i]] >= dep[b])
        {
            sol = max(sol,dp[a][i]);
            a = f[a][i];
        }

    if(a == b)return sol;

    for(int i = LG - 1; i >= 0; --i)
        if(f[a][i] != f[b][i])
    {
        sol = max(sol,max(dp[a][i],dp[b][i]));
        a = f[a][i];
        b = f[b][i];
    }

    return max(sol,max(dp[a][0],dp[b][0]));
}

int main()
{
    cin>>n>>m>>k;

    get_tree();

    Dfs(1,0);

    while(k--)
    {
        cin>>a>>b;
        cout<<get_sol(a,b)<<'\n';
    }
    return 0;
}