Cod sursa(job #2546981)

Utilizator Horia14Horia Banciu Horia14 Data 14 februarie 2020 19:40:29
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include<fstream>
#include<iostream>
#include<vector>
#include<algorithm>
#define MAX_EDGES 400000
#define MAX_VERTICES 200000
using namespace std;

struct edge {
    int x, y, c;
};

vector<edge> v;
vector<pair<int, int>> apm;
int p[MAX_VERTICES + 1], h[MAX_VERTICES + 1], n, m, minCost;

void readGraph() {
    int a, b, c, i;
    ifstream fin("apm.in");
    fin >> n >> m;
    for(i = 0; i < m; i++) {
        fin >> a >> b >> c;
        v.push_back({a, b, c});
    }
    fin.close();
}

class ComparEdge {
public:
    bool operator() (const edge& e1, const edge& e2) {
        return e1.c < e2.c;
    }
} myObj;

void Init(int n) {
    for(int i = 1; i <= n; i++) {
        p[i] = i;
        h[i] = 1;
    }
}

int Find(int x) {
    int r, aux;
    r = x;
    while(p[r] != r)
        r = p[r];
    while(p[x] != r) {
        aux = p[x];
        p[x] = r;
        x = aux;
    }
    return r;
}

void Union(int x, int y, int val) {
    int rootx, rooty;
    rootx = Find(x);
    rooty = Find(y);
    if(rootx != rooty) {
        if(h[rootx] < h[rooty])
            p[rootx] = rooty;
        else if(h[rootx] > h[rooty])
            p[rooty] = rootx;
        else {
            p[rootx] = rooty;
            h[rooty]++;
        }
        apm.push_back({x, y});
        minCost += val;
    }
}

void Kruskal() {
    int i = 0;
    sort(v.begin(), v.end(), myObj);
    Init(n);
    while(apm.size() < n - 1) {
        Union(v[i].x, v[i].y, v[i].c);
        i += 1;
    }
}

void printAPM() {
    vector<pair<int, int>>::iterator it;
    ofstream fout("apm.out");
    fout << minCost << "\n" << apm.size() << "\n";
    for(it = apm.begin(); it != apm.end(); ++it)
        fout << (*it).first << " " << (*it).second << "\n";
    fout.close();
}

int main() {
    readGraph();
    Kruskal();
    printAPM();
    return 0;
}