Cod sursa(job #2286603)

Utilizator andrei42Oandrei42O andrei42O Data 20 noiembrie 2018 16:01:56
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <bits/stdc++.h>
#define FISIERE 1
using namespace std;
#if FISIERE
string file_name="apm";
ifstream f(file_name+".in");
ofstream g(file_name+".out");
#endif
const int N = 100010;
int n,m,c,x,y,rx,ry,T[N],costAPM,getRoot(int);
vector<tuple<int,int,int>> M;
vector<pair<int,int>>sol;
int main()
{
    f>>n>>m;

    for(int i = 1 ; i <= n; i++)
        T[i]=i;

    for(;m;m--)
    {
        f >> x >> y >> c;
        M.push_back(make_tuple(c,x,y));
    }

    sort(M.begin(),M.end());

    for(auto it:M)
    {
        tie(c,x,y)=it;
        rx = getRoot(x);
        ry = getRoot(y);
        if(rx!=ry)
        {
            T[rx]=ry;
            costAPM+=c;
            sol.push_back(make_pair(x,y));
        }
    }

    g<<costAPM<<'\n'<<n-1<<'\n';

    for(auto it:sol)
        g<<it.first<<' '<<it.second<<'\n';

    return 0;
}
int getRoot(int nod)
{
    if(nod==T[nod])
        return nod;
    T[nod]=getRoot(T[nod]);
    return T[nod];
}