Cod sursa(job #2885511)

Utilizator iancupoppPopp Iancu Alexandru iancupopp Data 6 aprilie 2022 10:18:04
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.23 kb
#include <bits/stdc++.h>

using namespace std;

const int N = 15e3 + 5;
const int LOG = 14;

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

struct TreeEdge {
  int to;
  int cost;
};

int sef[N], sz[N], up[N][LOG], maxi[N][LOG], niv[N];
vector<TreeEdge> f[N];

int sefsuprem(int nod) {
  if (sef[nod] == nod)
    return nod;
  return sefsuprem(sef[nod]);
}

void dfs(int nod) {
  for (auto vec: f[nod]) {
    niv[vec.to] = niv[nod] + 1;
    up[vec.to][0] = nod;
    for (int i = 1; i < LOG; ++i)
      up[vec.to][i] = up[up[vec.to][i - 1]][i - 1];
    maxi[vec.to][0] = vec.cost;
    for (int i = 1; i < LOG; ++i)
      maxi[vec.to][i] = max(maxi[vec.to][i - 1], maxi[up[vec.to][i - 1]][i - 1]);
    dfs(vec.to);
  }
}

int lca(int a, int b) {
  if (niv[a] > niv[b])
    swap(a, b);
  int diff = niv[b] - niv[a], ans = 0;
  for (int i = 0; i < LOG; ++i)
    if (diff & (1 << i)) {
      ans = max(ans, maxi[b][i]);
      b = up[b][i];
    }
  if (a == b)
    return ans;
  for (int i = LOG - 1; i >= 0; --i)
    if (up[a][i] != up[b][i]) {
      ans = max(ans, max(maxi[a][i], maxi[b][i]));
      a = up[a][i];
      b = up[b][i];
    }
  ans = max(ans, max(maxi[a][0], maxi[b][0]));
  return ans;
}

int main() {
  ifstream cin("radiatie.in");
  ofstream cout("radiatie.out");
  int n, m, q;
  cin >> n >> m >> q;
  vector<Edge> e;
  while (m--) {
    int x, y, cost;
    cin >> x >> y >> cost;
    e.push_back({x, y, cost});
  }
  sort(e.begin(), e.end());
  for (int i = 1; i <= n; ++i) {
    sef[i] = i;
    sz[i] = 1;
  }
  for (auto i: e) {
    int sef_x = sefsuprem(i.x);
    int sef_y = sefsuprem(i.y);
    if (sef_x != sef_y) {
      if (sz[sef_x] < sz[sef_y]) {
        sef[sef_x] = sef_y;
        sz[sef_y] += sz[sef_x];
        f[sef_y].push_back({sef_x, i.cost});
      } else {
        sef[sef_y] = sef_x;
        sz[sef_x] += sz[sef_y];
        f[sef_x].push_back({sef_y, i.cost});
      }
    }
  }
  for (int i = 1; i <= n; ++i)
    if (sef[i] == i)
      dfs(i);
  while (q--) {
    int a, b;
    cin >> a >> b;
    cout << lca(a, b) << "\n";
  }
  cin.close();
  cout.close();
  return 0;
}