Cod sursa(job #2601131)

Utilizator AlexPop28Pop Alex-Nicolae AlexPop28 Data 13 aprilie 2020 20:24:47
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.38 kb
#include <bits/stdc++.h>
#define dbg() cerr <<
#define name(x) (#x) << ": " << (x) << ' ' <<

using namespace std;

struct DSU {
  int n;
  vector<int> dad, rnk, vis, cost;
  DSU(int n_) : n(n_), dad(n, -1), rnk(n, 1), vis(n), cost(n) {}

  int Find(int x) {
    if (dad[x] == -1) return x;
    return Find(dad[x]);
  }

  void Union(int x, int y, long long c) {
    x = Find(x), y = Find(y);
    if (x == y) return;

    if (rnk[x] < rnk[y]) swap(x, y);
    dad[y] = x;
    cost[y] = c;
    rnk[x] += rnk[x] == rnk[y];
  }

  int LCA(int x, int y) {
    static int vis_cnt = 0;
    ++vis_cnt;
    while (x != -1) vis[x] = vis_cnt, x = dad[x];
    while (vis[y] != vis_cnt) y = dad[y];
    return y;
  }
  
  int Query(int x, int y) {
    int ans = 0;
    int lca = LCA(x, y);
    while (x != lca) ans = max(ans, cost[x]), x = dad[x];
    while (y != lca) ans = max(ans, cost[y]), y = dad[y];
    return ans;
  }
};

int main() {
  ifstream cin("radiatie.in");
  ofstream cout("radiatie.out");

  int n, m, k; cin >> n >> m >> k;
  vector<tuple<int, int, int>> edges;
  while (m--) {
    int a, b, c; cin >> a >> b >> c;
    edges.emplace_back(c, a - 1, b - 1);
  }
  sort(edges.begin(), edges.end());

  DSU dsu(n);
  for (auto &e : edges) {
    int cost, a, b; tie(cost, a, b) = e;
    dsu.Union(a, b, cost);
  }
  while (k--) {
    int a, b; cin >> a >> b;
    cout << dsu.Query(a - 1, b - 1) << '\n';
  }
}