Cod sursa(job #3237499)

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

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

const int MAX_NUM = 15100;

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;
        int findX = find(x), findY = find(y);
        if (findX != findY) {
            for (int j = 0; j < k; ++j) {
                int x1 = queries[j].first, y1 = queries[j].second;
                int findX1 = find(x1), findY1 = find(y1);
                if ((findX1 == findX && findY1 == findY) ||
                    (findX1 == findY && findY1 == findX)) {
                    answer[j] = c;
                }
            }
            unify(x, y);
        }
    }
    for (int ans : answer) {
        fout << ans << "\n";
    }
    return 0;
}