Cod sursa(job #2341730)

Utilizator Dobricean_IoanDobricean Ionut Dobricean_Ioan Data 12 februarie 2019 10:24:58
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.08 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;
ifstream fin ("radiatie.in");
ofstream fout ("radiatie.out");
 
const int MAXN = 15001;
const int MAXM = 30001;
const int LOg = 18;
 
vector<pair<int, int> >G[MAXN + 5];
 
struct Edge {
  int u, v, c;
  bool operator < (const Edge& other) const {
    return c < other.c;
  }
}E[MAXM + 5];
 
int t[MAXN + 5], h[MAXN + 5];
 
int find(int x);
int Union(int x, int y);
int rmq[LOg + 5][MAXN + 5];
int T[LOg + 5][MAXN + 5];
int hh[MAXN + 5];
 
void dfs(int node, pair<int, int> f) {
  
  T[0][node] = f.first;
  rmq[0][node] = f.second;
  hh[node] = 1 + hh[f.first];
  for (int i = 1; i <= LOg; ++i) {
    T[i][node] = T[i - 1][T[i - 1][node]];
    rmq[i][node] = max(rmq[i - 1][node], rmq[i - 1][T[i - 1][node]]);
  }
  for (auto it:G[node])
    if (it.first != f.first)
      dfs(it.first, {node, it.second});
}
 
int query(int x, int y) {
  int ans = 0;
  if (hh[x] < hh[y])
    swap(x, y);
  for (int i = LOg; i >= 0; --i)
    if (hh[x] - (1 << i) >= hh[y]) {
      ans = max(ans, rmq[i][x]);
      x = T[i][x];
    }
  for (int i = LOg; i >= 0; --i)
    if (hh[x] - (1 << i) > 0 && T[i][x] != T[i][y]) {
      ans = max(ans, max(rmq[i][x], rmq[i][y]));
      x = T[i][x];
      y = T[i][y];
    }
  if (x != y)
    ans = max(ans, max(rmq[0][x], rmq[0][y]));
  return ans;
}
 
int main() {
 
  int n, m, k;
  
  fin >> n >> m >> k;
  for (int i = 1; i <= m; ++i)
   fin >> E[i].u >> E[i].v >> E[i].c;
 
  sort(E + 1, E + m + 1);
 
  for (int i = 1; i <= n; ++i)
    t[i] = i;
 
  for (int i = 1; i <= m; ++i)
    if (Union(E[i].u, E[i].v)) {
		G[E[i].u].push_back({E[i].v, E[i].c});
		G[E[i].v].push_back({E[i].u, E[i].c});
	}
 
  dfs(1, {0, 0});
 
  for (int i = 1; i <= k; ++i) {
    int x, y;
    fin >> x >> y;
    fout << query(x,y) << "\n";
  }
 
  return 0;
}
int find(int x) {
  if (t[x] == x)
    return x;
  int aux = find(t[x]);
  t[x] = aux;
  return aux;
}
 
int Union(int x, int y) {
  x = find(x);
  y = find(y);
  if (x == y)
    return 0;
  if (h[x] < h[y])
    swap(x, y);
  if (h[x] == h[y])
    h[x]++;
  t[y] = x;
  return 1;
}