Cod sursa(job #2545791)

Utilizator sichetpaulSichet Paul sichetpaul Data 13 februarie 2020 15:30:35
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.5 kb
#include <bits/stdc++.h>
#define Nmax 30005
using namespace std;

ifstream f("radiatie.in");
ofstream g("radiatie.out");

int N, M, K, Q, pos;
int h[Nmax], t[Nmax], val[Nmax], lev[Nmax];
vector<int> G[Nmax];
struct edge{
    int x, y, c;
};
edge v[Nmax];
bool cmp(edge a, edge b) {
   return a.c < b.c;
}
int root(int x) {
    while (t[x]) x = t[x];
    return x;
}

void DFS(int node, int father) {
    lev[node] = lev[father] + 1;
    for (auto it: G[node])
        DFS(it, node);
}
int lca(int x, int y) {
    int ans = 0;
    while (lev[x] > lev[y])
        ans = max(ans, val[x]), x = t[x];

    while (x != y) {
        ans = max(ans, max(val[x], val[y]));
        x = t[x], y = t[y];
    }
      return ans;
}
int main()
{
    f >> N >> M >> Q;
    for (int i = 1; i <= M; ++i)
        f >> v[i].x >> v[i].y >> v[i].c;
    sort(v + 1, v + M + 1, cmp);

    for (int i = 1; i <= M; ++i)
    if (root(v[i].x) != root(v[i].y)) {
        int x = root(v[i].x), y = root(v[i].y);
        if (h[x] >= h[y]) {
            G[x].push_back(y), pos = x;
            t[y] = x;
            val[y] = v[i].c;
        }

        else {
            G[y].push_back(x), pos = y;
            t[x] = y;
            val[x] = v[i].c;
        }
          if (h[x] == h[y]) ++h[x];
    }
       DFS(pos, 0);

    for (int q = 1; q <= Q; ++q) {
        int x, y;
        f >> x >> y;
        if (lev[x] < lev[y]) swap(x, y);
        g << lca(x, y) << '\n';
    }

    return 0;
}