Cod sursa(job #1824450)

Utilizator Andrei1998Andrei Constantinescu Andrei1998 Data 7 decembrie 2016 20:54:05
Problema Radiatie Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.61 kb
#include <fstream>
#include <algorithm>

using namespace std;

class InputReader {
public:
    InputReader() {}
    InputReader(const char *file_name) {
        input_file = fopen(file_name, "r");
        cursor = 0;
        fread(buffer, SIZE, 1, input_file);
    }
    inline InputReader &operator >>(int &n) {
        while(buffer[cursor] < '0' || buffer[cursor] > '9') {
            advance();
        }
        n = 0;
        while('0' <= buffer[cursor] && buffer[cursor] <= '9') {
            n = n * 10 + buffer[cursor] - '0';
            advance();
        }
        return *this;
    }
private:
    FILE *input_file;
    static const int SIZE = 1 << 17;
    int cursor;
    char buffer[SIZE];
    inline void advance() {
        ++ cursor;
        if(cursor == SIZE) {
            cursor = 0;
            fread(buffer, SIZE, 1, input_file);
        }
    }
};

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()
{
    InputReader cin("radiatie.in");
    ofstream cout("radiatie.out");

    cin >> n >> m >> k;

    for (int i = 1; i <= m; ++ i) {
        int a, b, c;
        cin >> 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;
        cin >> a >> b;
        cout << solve(a, b) << '\n';
    }
    return 0;
}