Cod sursa(job #1921406)

Utilizator raduaxel1Dilirici Radu raduaxel1 Data 10 martie 2017 12:34:20
Problema Arbore partial de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <iostream>
#include <fstream>

using namespace std;

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

struct muchii
{
    int nod1, nod2, cost, folosit;
}v[400003], aux;

int n, m, x, y, nr, suma;
int N[200003];

int parinte(int a){
    while (N[a]!=N[N[a]])
        N[a]=N[N[a]];
    return N[a];
}

int main()
{
    fin>>n>>m;
    for (int i=1; i<=m; i++){
        fin>>v[i].nod1>>v[i].nod2>>v[i].cost;
    }
    for (int i=1; i<m; i++)
        for (int j=i+1; j<=m; j++)
        if (v[i].cost>v[j].cost){
            aux=v[i];
            v[i]=v[j];
            v[j]=aux;
        }
    for (int i=1; i<=n; i++)
        N[i]=i;
    for (int i=1; i<=m; i++){
        int rx, ry;
        rx=parinte(v[i].nod1);
        ry=parinte(v[i].nod2);
        if (rx!=ry){
            suma+=v[i].cost;
            nr++;
            N[rx]=ry;
            v[i].folosit=1;
        }
    }
    fout<<suma<<"\n";
    fout<<nr<<"\n";
    for (int i=1; i<=m; i++){
        if (v[i].folosit==1){
            fout<<v[i].nod1<<" "<<v[i].nod2<<"\n";
        }
    }
    return 0;
}