Cod sursa(job #3163168)

Utilizator ionut3007Malita Ionut ionut3007 Data 30 octombrie 2023 19:02:31
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

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

const int nmax=400005;

pair<int,int> P[nmax];

int n,m,total,t[nmax],rg[nmax],k;

struct muchie{
    int x,y,c;
}v[nmax];

bool comp(muchie a,muchie b){
    return a.c<b.c;
}

void Fin(){
    fin>>n>>m;
    for(int i=1;i<=m;i++)
        fin>>v[i].x>>v[i].y>>v[i].c;

    sort(v+1,v+m+1,comp);

    for(int i=1;i<=n;i++)
        t[i]=i,rg[i]=1;
}

int cauta(int x){
    while(t[x]!=x)
        x=t[x];
    return x;
}

int unire(int x,int y){
    if(rg[x]<rg[y])
        t[x]=y;
    if(rg[x]>rg[y])
        t[y]=x;
    if(rg[x]==rg[y]){
        t[x]=y;
        rg[y]++;
    }
}

void kruskal(){
    for(int i=1;i<=m;i++){
        if(cauta(v[i].x)!=cauta(v[i].y)){
            unire(cauta(v[i].x),cauta(v[i].y));
            P[++k].first=v[i].x;
            P[k].second=v[i].y;
            total+=v[i].c;
        }
    }
}

void afisare(){
    fout<<total<< '\n';
    fout<<n-1<<'\n';
    for(int i=1;i<=k;i++)
    fout<<P[i].first<< " "<<P[i].second<< '\n';
}

int main()
{
    Fin();
    kruskal();
    afisare();
    return 0;
}