Cod sursa(job #2529089)

Utilizator Bogdan2728Iamnitchi Bogdan Bogdan2728 Data 22 ianuarie 2020 22:20:57
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("apm.in");
ofstream g("apm.out");

const int Nmax = 400005;
int n,m,k,total,tata[Nmax],rang[Nmax];

pair <int,int> arb[Nmax];

struct Muchie{
    int x,y,cost;
}v[Nmax];

bool Compare(Muchie a,Muchie b){
    return a.cost < b.cost;
}

void Read(){

    f>>n>>m;
    for(int i=1;i<=m;i++)
        f>>v[i].x>>v[i].y>>v[i].cost;

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

    for(int i=1;i<=n;i++){
        tata[i]=i;
        rang[i]=1;
    }
}

int Find(int nod)
{
    while(nod != tata[nod])
        nod = tata[nod];
    return nod;
}

void Unire(int x,int y){
    if(rang[x] < rang[y])
        tata[x] = y;
    if(rang[x] > rang[y])
        tata[y] = x;
    if(rang[x] == rang[y]){
        tata[x] = y;
        rang[y]++;
    }
}

void Afisare(){

    g<<total<<"\n";
    g<<k<<"\n";

    for(int i=1;i<=k;i++)
        g<<arb[i].first<<" "<<arb[i].second<<"\n";
}
void Solve(){
    for(int i=1;i<=m;i++){
        int tata_x = Find(v[i].x);
        int tata_y = Find(v[i].y);
        if(tata_x != tata_y){
            Unire(tata_x ,tata_y);
            arb[++k].first = v[i].x;
            arb[k].second = v[i].y;
            total += v[i].cost;
        }
    }
    Afisare();
}
int main()
{
    Read();
    Solve();
    return 0;
}