Nu exista pagina, dar poti sa o creezi ...

Cod sursa(job #3278104)

Utilizator Cris24dcAndrei Cristian Cris24dc Data 18 februarie 2025 17:56:16
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.43 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <bitset>
#include <vector>
#include <array>
#include <stack>
#include <algorithm>

#define maxSize 100001

using namespace std;

vector<array<int, 3>> readEdgeListWeighted(ifstream &fin, int nodes, int edges) {
    vector<array<int, 3>> edgeList;
    for (int i = 0; i < edges; i++) {
        int x, y, weight;
        fin >> x >> y >> weight;
        edgeList.push_back({x, y, weight});
    }
    return edgeList;
}

struct dsu {
    vector<int> root;
    vector<int> height;

    dsu(int n) {
        height.resize(n+1, 0);
        root.resize(n+1);
        for (int i = 1; i <= n; i++) {
            root[i] = i;
        }
    }

    int findRoot(int node) {
        if (node != root[node]) {
            root[node] = findRoot(root[node]);
        }
        return root[node];
    }

    void unionNodes(int u, int v) {
        int rootU = findRoot(u);
        int rootV = findRoot(v);
        if(rootU == rootV) {
            return;
        }
        if(height[rootU] < height[rootV]) {
            root[rootU] = rootV;
        }
        else if(height[rootU] > height[rootV]) {
            root[rootV] = rootU;
        }
        else {
            root[rootU] = rootV;
            height[rootV]++;
        }
    }

    bool areConnected(int u, int v) {
        return findRoot(u) == findRoot(v);
    }
};

vector<array<int, 3>> kruskal(int& finalCost,const int& nodes, vector<array<int, 3>> &edgeList) {
    sort(edgeList.begin(), edgeList.end(), [](const array<int, 3>& a, const array<int, 3>& b) {
        return a[2] < b[2];
    });

    dsu dsu(nodes);

    vector<array<int, 3>> mst;

    for (const auto& edge : edgeList) {
        int u = edge[0];
        int v = edge[1];
        int weight = edge[2];

        if (!dsu.areConnected(u, v)) {
            finalCost += weight;
            mst.push_back(edge);
            dsu.unionNodes(u, v);
        }

        if (mst.size() == nodes - 1) {
            break;
        }
    }

    return mst;
}

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

    int finalCost = 0;
    int nodes, edges;
    fin >> nodes >> edges;

    auto edgeList = readEdgeListWeighted(fin, nodes, edges);

    auto mst = kruskal(finalCost, nodes, edgeList);

    fout << finalCost << endl;
    fout << mst.size() << endl;
    for (auto elem : mst) {
        fout << elem[1] << " " << elem[0] << endl;
    }

    fin.close();
    fout.close();

    return 0;
}