Cod sursa(job #3285142)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 12 martie 2025 16:04:14
Problema Radiatie Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.23 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 15e3 + 3;
const int LOGMAX = 20;

int n, m, q;
int t[NMAX], depth[NMAX];
int up[NMAX][LOGMAX], val[NMAX][LOGMAX];

struct Edge {
    int x, y, w;
    bool operator<(const Edge &other) {
        return w < other.w;
    }
};

vector<Edge> edges;
vector<vector<pair<int, int>>> g;

int find(int node) {
    if(t[node] == node) { return node; }
    return (t[node] = find(t[node]));
}

void unite(int x, int y) {
    t[find(x)] = find(y);
}

void dfs(int node, int parent) {
    depth[node] = depth[parent] + 1;
    up[node][0] = parent;
    for(auto [son, w] : g[node]) {
        if(son == parent) { continue; }
        val[son][0] = w;
        dfs(son, node);
    }
}

int query(int x, int y) {
    if(depth[x] < depth[y]) { swap(x, y); }
    int ans = 0, diff = depth[x] - depth[y];
    for(int i = LOGMAX - 1; i >= 0; i--) {
        if((1 << i) & diff) {
            ans = max(ans, val[x][i]);
            x = up[x][i];
        }
    }
    if(x == y) {
        return ans;
    }
    for(int i = LOGMAX - 1; i >= 0; i--) {
        if(up[x][i] != up[y][i]) {
            ans = max(ans, max(val[x][i], val[y][i]));
            x = up[x][i];
            y = up[y][i];
        }
    }
    ans = max(ans, val[x][0]);
    return ans;
}

int main() {

    in >> n >> m >> q;

    for(int i = 1; i <= m; i++) {
        int x, y, w;
        in >> x >> y >> w;
        edges.push_back({x, y, w});
    }

    sort(edges.begin(), edges.end());

    for(int i = 1; i <= n; i++) {
        t[i] = i;
    }

    g.resize(n + 1);
    for(auto e : edges) {
        if(find(e.x) != find(e.y)) {
            unite(e.x, e.y);
            g[e.x].push_back({e.y, e.w});
            g[e.y].push_back({e.x, e.w});
        }
    }


    dfs(1, 0);

    for(int j = 1; j < LOGMAX; j++) {
        for(int i = 1; i <= n; i++) {
            up[i][j] = up[up[i][j - 1]][j - 1];
            val[i][j] = max(val[i][j - 1], val[up[i][j - 1]][j - 1]);
        }
    }

    while(q--) {
        int x, y;
        in >> x >> y;
        out << query(x, y) << '\n';
    }

    return 0;
}