Cod sursa(job #1700940)

Utilizator panteapaulPantea Paul panteapaul Data 11 mai 2016 20:05:22
Problema Arbore partial de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <fstream>
#include <set>
#include <map>
#include <deque>

using namespace std;

typedef pair<int,int> paer;

struct nod {
    nod *parent = 0;
    int heit = 1;
};

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;
    }

    deque<paer> deck;

    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;

            if (t1->heit > t2->heit) {
                t2->parent = t1;
            }
            else {
                t1->parent = t2;
                t2->heit = max(t2->heit, t1->heit + 1);
            }

            deck.push_back(paer(p.second.first, p.second.second));
        }
    }

    out<<suma<<endl;
    out<<deck.size()<<endl;
    for (i=0; i<deck.size(); i++) {
        out<<deck[i].first<<" "<<deck[i].second<<endl;
    }

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