Cod sursa(job #2504574)

Utilizator lucametehauDart Monkey lucametehau Data 5 decembrie 2019 11:00:46
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.39 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

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

int n, m, k, x, y, z;

vector <Edge> edge;
int t[15005], rang[15005], cost[15005];

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

void dfs(int nod) {
  if(rang[nod])
    return;
  if(nod == t[nod]) {
    rang[nod] = 1;
    return;
  }
  dfs(t[nod]);
  rang[nod] = rang[t[nod]] + 1;
}

int main() {
  cin >> n >> m >> k;
  for(int i = 0; i < m; i++) {
    cin >> x >> y >> z;
    edge.push_back({x, y, z});
  }
  for(int i = 1; i <= n; i++)
    t[i] = i;
  sort(edge.begin(), edge.end());
  for(int i = 0; i < m; i++) {
    int tx = find(edge[i].x), ty = find(edge[i].y);
    if(tx != ty)
      t[ty] = tx, cost[ty] = edge[i].z;
  }
  for(int i = 1; i <= n; i++)
    dfs(i);
  for(int i = 1; i <= k; i++) {
    cin >> x >> y;
    int ans = 0;
    while(x != y) {
      if(rang[x] > rang[y]) {
        ans = max(ans, cost[x]);
        x = t[x];
      } else if(rang[x] < rang[y]) {
        ans = max(ans, cost[y]);
        y = t[y];
      } else {
        ans = max(ans, max(cost[x], cost[y]));
        x = t[x], y = t[y];
      }
    }
    cout << ans << "\n";
  }
  return 0;
}