Cod sursa(job #2444152)

Utilizator ApostolIlieDanielApostol Daniel ApostolIlieDaniel Data 30 iulie 2019 13:50:44
Problema Radiatie Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.52 kb
#include <bits/stdc++.h>

using namespace std;

int n;

struct Edge {
    int x;
    int y;
    int c;
};

const int M = 3e4, N = 16e3;

Edge gr[1 + M];
int h[1 + N], f[1 + N], cost[1 + N];
bool cmp (Edge a, Edge b) {
    return a.c < b.c;
}


void dfs (int node) {
    if (h[node])
        return;
    if (f[node] == node){
        h[node] = 1;
        return;
    }
    dfs (f[node]);
    h[node] = h[f[node]] + 1;
}

int ft (int x) {
    return (f[x] == x) ? x : ft (f[x]);
}

int main() {
    int n, m, k;
    freopen ("radiatie.in", "r", stdin);
    freopen ("radiatie.out", "w", stdout);
    cin >> n >> m >> k;
    for (int i = 1; i <= m; i++) {
        int x, y, c;
        cin >> x >> y >> c;
        gr[i] = {x, y, c};
    }
    sort (gr + 1, gr + m + 1, cmp);
    for (int i = 1; i <= n; i++)
        f[i] = i;
    for (int i = 1; i <= m; i++) {
        int tx = ft (gr[i].x), ty = ft (gr[i].y);
        if (tx != ty)
            f[ty] = tx, cost[ty] = gr[i].c;
    }
    for (int i = 1; i <= n; i++)
        dfs (i);
    while (k--) {
        int x, y;
        cin >> x >> y;
        int ans = 0;
        while (h[x] > h[y]) {
            ans = max (ans, cost[x]);
            x = f[x];
        }
        while (h[y] > h[x]) {
            ans = max (ans, cost[y]);
            y = f[y];
        }
        while (y != x) {
            ans = max (ans, max (cost[x], cost[y]));
            y = f[y], x = f[x];
        }
        cout << ans << "\n";
    }
    return 0;
}