Cod sursa(job #3210282)

Utilizator Maftei_TudorMaftei Tudor Maftei_Tudor Data 5 martie 2024 20:34:49
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.41 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>

#define fi first
#define sc second

using namespace std;
typedef pair<int, int> pii;
const int N = 15005;

struct muchie {
    int x, y, c;
};

int n, m, q, timer, tin[N], tout[N], dsu[N];
pii up[N][20];
vector<pii> g[N];

int get(int x) {
    if(x == dsu[x])
        return x;
    else return dsu[x] = get(dsu[x]);
}
void join(int a, int b) {
    int pa = get(a);
    int pb = get(b);

    dsu[pa] = pb;
}
void dfs(int nod = 1, int p = 0) {
    tin[nod] = ++timer;

    for(auto nxt : g[nod])
        if(nxt.sc == p) {
            up[nod][0] = {nxt.fi, p};
            for(int i=1; i<=log2(n); i++)
                up[nod][i] = {max(up[nod][i-1].fi, up[up[nod][i-1].sc][i-1].fi), up[up[nod][i-1].sc][i-1].sc};

            break;
        }
    for(auto nxt : g[nod])
        if(nxt.sc != p)
            dfs(nxt.sc, nod);

    tout[nod] = timer;
}
bool ancestor(int a, int b) {
    return tin[a] <= tin[b] && tout[b] <= tout[a];
}
int get_lca(int a, int b) {
    if(ancestor(a, b))
        return a;
    if(ancestor(b, a))
        return b;

    for(int i=log2(n); i>=0; i--)
        if(up[a][i].sc && !ancestor(up[a][i].sc, b))
            a = up[a][i].sc;
    return up[a][0].sc;
}
int maxpath(int a, int b) {
    if(a == b)
        return 0;
    int ans = 0;
    for(int i=log2(n); i>=0; i--)
        if(up[a][i].sc && !ancestor(up[a][i].sc, b)) {
            ans = max(ans, up[a][i].fi);
            a = up[a][i].sc;
        }
    return max(ans, up[a][0].fi);
}

int main()
{
    freopen("radiatie.in", "r", stdin);
    freopen("radiatie.out", "w", stdout);
    cin.tie(nullptr)->sync_with_stdio(0);

    cin >> n >> m >> q;
    vector<muchie> mc(m);
    for(int i=0; i<m; i++)
        cin >> mc[i].x >> mc[i].y >> mc[i].c;

    sort(mc.begin(), mc.end(), [&](muchie a, muchie b) {
        return a.c < b.c;
    });
    for(int i=1; i<=n; i++)
        dsu[i] = i;
    for(int i=0; i<m; i++)
        if(get(mc[i].x) != get(mc[i].y)) {
            g[mc[i].x].push_back({mc[i].c, mc[i].y});
            g[mc[i].y].push_back({mc[i].c, mc[i].x});
            join(mc[i].x, mc[i].y);
        }

    dfs();
    while(q--) {
        int x, y;
        cin >> x >> y;
        int lca = get_lca(x, y);
        cout << max(maxpath(x, lca), maxpath(y, lca)) << '\n';
    }
    return 0;
}