Cod sursa(job #1288841)

Utilizator thesvcoolmanLucian Bicsi thesvcoolman Data 9 decembrie 2014 08:57:48
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.93 kb
#include <fstream>
#include<vector>
#include<algorithm>

using namespace std;

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

class Edge {
    public:
    int v1, v2, cost;
    Edge(int V1, int V2, int c) {
        v1 = V1;
        v2 = V2;
        cost = c;
    }
    void print() {
        fout<<v1<<" "<<v2<<" "<<'\n';
    }
};

class Graph {
    public:
    int n;
    vector<Edge> E;
    void addEdge(int a, int b, int c) {
        Edge e(a, b, c);
        E.push_back(e);
    }
}G;

vector<int> PARENT;
vector<int> RANK(G.n, 0);
vector<Edge> EDGES;

void makeSets(int n) {

    PARENT.resize(n);
    RANK.resize(n);

    for(int i=0; i<n; i++) {
        PARENT[i] = i;
        RANK[i] = 0;
    }
}

void unite (int root1, int root2) {
    if(RANK[root1]<RANK[root2]) {
        PARENT[root1] = root2;
    }
    else if(RANK[root2]>RANK[root1]) {
        PARENT[root2] = root1;
    }
    else {
        PARENT[root2] = root1;
        RANK[root1] ++;
    }
}

int findRoot(int node) {
    if(PARENT[node] == node) {
        return node;
    }
    else {
        return findRoot(PARENT[node]);
    }
}

bool cmp(Edge a, Edge b) {
    return (a.cost < b.cost);
}

int Kruskal (Graph &G) {
    makeSets(G.n);
    int total = 0;

    sort(G.E.begin(), G.E.end(), cmp);

    for(int i=0; i<G.E.size(); i++) {
        Edge e = G.E[i];
        int r1 = findRoot(e.v1);
        int r2 = findRoot(e.v2);
        if(r1!=r2) {
            unite(r1, r2);
            EDGES.push_back(e);
            total += e.cost;
        }
    }

    return total;

}



int main()
{
    int m, a, b, c;
    fin>>G.n>>m;
    G.n ++;
    for(int i=0; i<m; i++) {
        fin>>a>>b>>c;
        G.addEdge(a, b, c);
    }

    int TOTAL = Kruskal(G);
    fout<<TOTAL<<'\n'<<EDGES.size()<<'\n';

    for(int i=0; i<EDGES.size(); i++) {
        EDGES[i].print();
    }
    return 0;
}