Cod sursa(job #2900536)

Utilizator iraresmihaiiordache rares mihai iraresmihai Data 11 mai 2022 09:12:34
Problema Radiatie Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.29 kb
#include <iostream>
#include <vector>
#include <algorithm>

#define MAXM 30000
#define MAXN 15000
#define MAX_LOG 14

using namespace std;

struct edge{
  int b, cost;
};

struct node{
  int lvl;
  bool visited;
  int parent, parentCost;
  vector <edge> children;
};

struct graphEdge{
  int a, b, cost;
};

bool comp(graphEdge a, graphEdge b) {
  return a.cost < b.cost;
}

graphEdge m[MAXM];
node tree[MAXN + 1];
int unions[MAXN + 1];

int findFather(int x) {
  if ( unions[x] == 0 )
    return x;
  return unions[x] = findFather(unions[x]);
}

void unite(int x, int y) {
  int fatherX, fatherY;

  fatherX = findFather(x);
  fatherY = findFather(y);

  if ( fatherX != fatherY )
    unions[fatherX] = fatherY;
}

void addEdge(int a, int b, int cost) {
  tree[a].children.push_back({b, cost});
  tree[b].children.push_back({a, cost});
}

void dfs(int pos, int level) {
  tree[pos].visited = true;
  tree[pos].lvl = level;

  for ( edge i : tree[pos].children ) {
    if ( !tree[i.b].visited ) {
      tree[i.b].parent = pos;
      tree[i.b].parentCost = i.cost;
      dfs(i.b, level + 1);
    }
  }
}

int solve(int a, int b) {
  int ans;

  ans = 0;

  if ( tree[a].lvl > tree[b].lvl )
    swap(a, b);

  while ( tree[a].lvl < tree[b].lvl ) {
    ans = max(ans, tree[b].parentCost);
    b = tree[b].parent;
  }

  while ( a != b ) {
    ans = max(ans, max(tree[a].parentCost, tree[b].parentCost));
    a = tree[a].parent;
    b = tree[b].parent;
  }

  return ans;
}

int main() {
  FILE *fin, *fout;
  fin = fopen("radiatie.in", "r");
  fout = fopen("radiatie.out", "w");

  int n, m2, i, k, fatherA, fatherB, a, b;

  fscanf(fin, "%d%d%d", &n, &m2, &k);

  for ( i = 0; i < m2; i++ ) {
    fscanf(fin, "%d%d%d", &m[i].a, &m[i].b, &m[i].cost);
  }

  sort(m, m + m2, comp);

  for ( i = 0; i < m2; i++ ) {
    fatherA = findFather(m[i].a);
    fatherB = findFather(m[i].b);

    if ( fatherA != fatherB ) {
      addEdge(m[i].a, m[i].b, m[i].cost);
      unite(m[i].a, m[i].b);
    }
  }

  for ( i = 1; i <= n; i++ ) {
    if ( !tree[i].visited )
      dfs(i, 1);
  }

  while ( k-- ) {
    fscanf(fin, "%d%d", &a, &b);

    fprintf(fout, "%d\n", solve(a, b));
  }

  fclose(fin);
  fclose(fout);

  return 0;
}