Cod sursa(job #2798221)

Utilizator linte_robertLinte Robert linte_robert Data 11 noiembrie 2021 00:32:03
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb

#include <iostream>
#include <fstream>
#include <vector>
#include <utility>

using namespace std;

int reprez( vector < int > &ind, int i ){
    if( ind[i] == i ) return i;
    ind[i] = reprez( ind, ind[i] );
    return ind[i];
}
void reuniune( vector < int > &ind, int i, int j ){
    ind[reprez(ind,i)] = reprez(ind,j);
}

int main(){
    ifstream fin("apm.in");
    ofstream fout("apm.out");
    int n;
    int m;
    fin >> n >> m;
    vector < vector < int > > lista_muchii;
    vector <vector < int > > apm;
    for( int i = 0; i < m; i++ ){
        int x, y, c;
        fin >> x >> y >> c;
        vector < int > muchie;
        muchie.push_back(x);
        muchie.push_back(y);
        muchie.push_back(c);
        lista_muchii.push_back(muchie);
    }
    for( int i = 0; i < lista_muchii.size(); i++ ){
        for( int j = 0; j < i; j++ ){
            if( lista_muchii[i][2] < lista_muchii[j][2] ){
                vector < int > aux(lista_muchii[i]);
                lista_muchii[i] = lista_muchii[j];
                lista_muchii[j] = aux;
            }
        }
    }
    vector < int > ind;
    for( int i = 0; i <= n; i++ ){
        ind.push_back(i);
    }
    int nrmsel = 0;
    int suma = 0;
    for( int i = 0; i < m; i++ ){
        if( reprez(ind, lista_muchii[i][0]) != reprez(ind, lista_muchii[i][1]) ){
            apm.push_back(lista_muchii[i]);
            suma += lista_muchii[i][2];
            reuniune(ind, lista_muchii[i][0], lista_muchii[i][1]);
            nrmsel++;
            if(nrmsel == n - 1){
                break;
            }
        }
    }
    fout << suma << endl << apm.size() << "\n";
    for( int i = 0; i < apm.size(); i++ ){
        fout << apm[i][0] << " " << apm[i][1] << " " << apm[i][2] << "\n";
    }
}