Cod sursa(job #1877568)

Utilizator PletoPletosu Cosmin-Andrei Pleto Data 13 februarie 2017 15:58:29
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
#define MMAX 400001
#define NMAX 200001

using namespace std;

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

struct muchie{
    int x, y, cost;
} A[MMAX];

int T[NMAX], RG[NMAX], S[NMAX];

bool comp(muchie i, muchie j) {
    return i.cost < j.cost;
}

int Find(int x) {
    int R = x, y;
    for(; R != T[R]; R = T[R]) ;
    while(x != T[x]) {
        y = T[x];
        T[x] = R;
        x = y;
    }
    return R;
}

void unite(int x, int y) {
    if(RG[x] > RG[y]) {
        T[y] = x;
    } else {
        T[x] = y;
    }
    if(RG[x] == RG[y]) RG[y]++;
}

int main() {
    int N, M, k = 0, sum = 0;
    fin>>N>>M;
    for(int i = 1; i <= M; ++i) {
        fin>>A[i].x>>A[i].y>>A[i].cost;
        T[i] = i;
        RG[i] = 1;
    }
    sort(A+1, A+M+1, comp);
    for(int i = 1; k < N-1; ++i) {
        if(Find(A[i].x) != Find(A[i].y)) {
            S[++k] = i;
            sum += A[i].cost;
            unite(Find(A[i].x), Find(A[i].y));
        }
    }
    fout<<sum<<'\n'<<k<<'\n';
    for(int i = 1; i <= k; ++i) {
        fout<<A[S[i]].x<<' '<<A[S[i]].y<<'\n';
    }
    return 0;
}