Cod sursa(job #2392618)

Utilizator alexilasiAlex Ilasi alexilasi Data 30 martie 2019 11:09:49
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.91 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 15000 + 5;
const int KMAX = NMAX;
const int MMAX = 2 * NMAX;

struct Edge {
    int a, b, c;
    Edge(int _a = 0, int _b = 0, int _c = 0):
        a(_a), b(_b), c(_c) {}
    friend bool operator<(const Edge &a, const Edge &b) {
        return a.c < b.c;
    }
} edges[MMAX];

int n, m, k;
vector <int> graph[NMAX];
int father[NMAX];
int h[NMAX];
int cost[NMAX];

void init() {
    for (int i = 1; i <= n; ++ i)
        father[i] = i;
}

int find(int node) {
    if (father[node] != father[father[node]])
        return find(father[node]);
    return father[node];
}

void unite(int a, int b, int val) {
    a = find(a), b = find(b);
    if (a == b)
        return ;

    if (h[a] < h[b]) {
        father[a] = b;
        cost[a] = val;
        graph[b].push_back(a);
    }
    else {
        if (h[a] == h[b])
            ++ h[a];
        father[b] = a;
        cost[b] = val;
        graph[a].push_back(b);
    }
}

void dfs(int node) {
    for (auto it: graph[node]) {
        h[it] = 1 + h[node];
        dfs(it);
    }
}

int solve(int a, int b) {
    int ans = 0;
    while (a != b)
        if (h[a] < h[b]) {
            ans = max(ans, cost[a]);
            a = father[a];
        }
        else {
            ans = max(ans, cost[b]);
            b = father[b];
        }
    return ans;
}

int main()
{
    ifstream fin("radiatie.in");
    ofstream fout("radiatie.out");

    fin >> n >> m >> k;

    for (int i = 1; i <= m; ++ i) {
        int a, b, c;
        fin >> a >> b >> c;
        edges[i] = Edge(a, b, c);
    }

    sort(edges + 1, edges + m + 1);

    init();

    for (int i = 1; i <= m; ++ i)
        unite(edges[i].a, edges[i].b, edges[i].c);

    while (k --) {
        int a, b;
        fin >> a >> b;
        fout << solve(a, b) << '\n';
    }
    return 0;
}