Cod sursa(job #3245544)

Utilizator Dia3141Costea Diana Stefania Dia3141 Data 29 septembrie 2024 13:02:10
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <algorithm>
#define mmax 400001
#define nmax 200001
using namespace std;
ifstream cin("apm.in");
ofstream cout("apm.out");
int n,m,cnt,apm,t[nmax];
struct muchie{
    int x,y,c;
    bool ok;
}v[mmax];
bool cmp(const muchie& a,const muchie& b){
    return a.c<b.c;
}
int get_root(int x){
    if(t[x]>0)
        return get_root(t[x]);
    return x;
}
void join(int x,int y){
    if(t[x]>t[y])
        swap(x,y);
    t[x]+=t[y];
    t[y]=x;
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        t[i]=-1;
    for(int i=1;i<=m;i++)
        cin>>v[i].x>>v[i].y>>v[i].c;
    sort(v+1,v+m+1,cmp);
    for(int i=1;i<=m&&cnt<n-1;i++){
        int rx=get_root(v[i].x),ry=get_root(v[i].y);
        if(rx!=ry){
            join(rx,ry);
            v[i].ok=1;
            apm+=v[i].c;
            cnt++;
        }
    }
    cout<<apm<<'\n'<<cnt<<'\n';
    for(int i=1;i<=m;i++)
        if(v[i].ok)
            cout<<v[i].x<<" "<<v[i].y<<'\n';
    return 0;
}