Cod sursa(job #1701399)

Utilizator panteapaulPantea Paul panteapaul Data 12 mai 2016 23:13:51
Problema Arbore partial de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>
#include <set>
#include <map>
#include <deque>

using namespace std;

typedef pair<int,int> paer;

struct nod {
    nod *parent = 0;
};

nod* top(nod *x) {

    nod* t = x;
    while (t->parent) {
        t = t->parent;
    }

    if (t != x) {
        x->parent = t;
    }

    return t;
}

int main()
{
    ifstream in("apm.in");
    ofstream out("apm.out");

    int n, m;
    in>>n>>m;

    set<pair<int, paer>> muchii;
    set<pair<int, paer>>::iterator it;

    int x, y, c, i;
    for (i=0; i<m; i++) {
        in>>x>>y>>c;
        paer p = paer(x, y);
        muchii.insert(pair<int, paer>(c, p));
    }

    nod* graf[n+1];
    for (i=1; i<=n; i++) {
        graf[i] = new nod;
    }

    paer apm[n-1];
    i = 0;

    int suma = 0;
    for (it = muchii.begin(); it != muchii.end(); it++) {
        pair<int, paer> p = *it;

        x = p.second.first;
        y = p.second.second;

        nod *t1 = top(graf[x]), *t2 = top(graf[y]);
        if (t1 != t2) {
            suma += p.first;

            t2->parent = t1;

            apm[i] = paer(p.second.first, p.second.second);
            i++;
        }
    }

    out<<suma<<endl;
    out<<n-1<<endl;
    for (i=0; i<n-1; i++) {
        out<<apm[i].first<<" "<<apm[i].second<<endl;
    }

    in.close();
    out.close();
    return 0;
}