Cod sursa(job #1702102)

Utilizator panteapaulPantea Paul panteapaul Data 14 mai 2016 15:21:53
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

typedef pair<int,int> paer;

int graf[200001];

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

int top(int x) {
    int t = x;

    while (graf[t]) {
        int p = graf[graf[t]];
        if (p) {
            graf[t] = p;
        }
        t = graf[t];
    }

    if (t != x) {
        graf[x] = t;
    }

    return t;
}

bool comp(muchie x, muchie y) {
    return x.c < y.c;
}

int main()
{
    ifstream in("apm.in");
    FILE *out = fopen("apm.out", "w");

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

    muchie lm[m];

    int i, j;
    for (i=0; i<m; i++) {
        in>>lm[i].x>>lm[i].y>>lm[i].c;
    }
    sort(lm, lm+m, comp);

    int h[n+1];
    std::fill(h, h+n+1, 0);

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

    int suma = 0;
    for (i = 0; i < m; i++) {

        int t1 = top(lm[i].x), t2 = top(lm[i].y);
        if (t1 != t2) {
            suma += lm[i].c;

            if (h[t1] > h[t2]) {
                graf[t2] = t1;
            }
            else {
                graf[t1] = t2;

                if (h[t1] == h[t2]) {
                    h[t2]++;
                }
            }

            apm[j] = paer(lm[i].x, lm[i].y);
            j++;
        }
    }

    fprintf(out, "%d\n%d\n", suma, n-1);
    for (i=0; i<n-1; i++) {
        fprintf(out, "%d %d\n", apm[i].first, apm[i].second);
    }

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