Cod sursa(job #3237496)

Utilizator SilviuC25Silviu Chisalita SilviuC25 Data 9 iulie 2024 13:40:23
Problema Radiatie Scor 30
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.53 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MAX_NUM = 15005;

int n, m, k, parent[MAX_NUM];
vector<pair<int, pair<int, int>>> cost;
vector<pair<int, int>> queries;
vector<int> answer;

int find(int i) {
    if (parent[i] != i) {
        parent[i] = find(parent[i]);
    }
    return parent[i];
}

void unify(int i, int j) {
    if (rand() & 1) {
        parent[find(j)] = find(i);
    } else {
        parent[find(i)] = find(j);
    }
}

int main() {
    fin >> n >> m >> k;
    for (int i = 0; i < m; ++i) {
        int a, b, c;
        fin >> a >> b >> c;
        cost.push_back({c, {a, b}});
    }
    sort(cost.begin(), cost.end());
    for (int i = 1; i <= n; ++i) {
        parent[i] = i;
    }
    for (int i = 0; i < k; ++i) {
        int x, y;
        fin >> x >> y;
        queries.push_back({x, y});
    }
    answer.resize(k);
    for (auto costPair : cost) {
        int x = costPair.second.first, y = costPair.second.second, c = costPair.first;
        if (find(x) != find(y)) {
            for (int j = 0; j < k; ++j) {
                int x1 = queries[j].first, y1 = queries[j].second;
                if ((find(x1) == find(x) && find(y1) == find(y)) ||
                    (find(x1) == find(y) && find(y1) == find(x))) {
                    answer[j] = c;
                }
            }
            unify(x, y);
        }
    }
    for (int ans : answer) {
        fout << ans << "\n";
    }
    return 0;
}