Cod sursa(job #2777885)

Utilizator Catalinu23Gavrila Catalin Catalinu23 Data 25 septembrie 2021 17:06:19
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>
using namespace std;

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

int n,m,s;
struct muchie
{
    int nod1, nod2, cost;
};

muchie v[400005];
int t[200005];
vector<muchie> sol;

inline bool cmp(const muchie A, const muchie B)
{
    return A.cost<B.cost;
}

void Union(int x, int y)
{
    t[x]=y;
}

int Find(int x)
{
    int y=x, aux;
    while(t[y])
        y = t[y];
    while(t[x])
    {
        aux = t[x];
        t[x] = y;
        x = aux;
    }
    return y;
}

void Citire()
{
    fin>>n>>m;
    for(int i=1; i<=m; i++)
        fin>>v[i].nod1>>v[i].nod2>>v[i].cost;
    sort(v+1, v+m+1, cmp);
}

int main()
{
    Citire();
    for(int i=1; i<=m; i++)
    {
        int tata1 = Find(v[i].nod1), tata2 = Find(v[i].nod2);
        if(tata1 != tata2)
        {
            Union(tata1, tata2);
            s += v[i].cost;
            sol.push_back(v[i]);
        }
    }
    fout<<s<<"\n"<<sol.size()<<"\n";
    for(auto it: sol)
        fout<<it.nod1<<" "<<it.nod2<<"\n";
    return 0;
}