Cod sursa(job #2028946)

Utilizator rangal3Tudor Anastasiei rangal3 Data 28 septembrie 2017 21:09:01
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>
#include <queue>
#include <vector>
#define in "apm.in"
#define out "apm.out"
#define N 200003

using namespace std;

ifstream fin(in);
ofstream fout(out);

int n,m,x,y,c;
long long S = 0;

int t[N];

priority_queue< pair<int, pair<int,int> > > coada;

vector< pair<int,int> > sol;

inline int root(int nod)
{
    int rad = nod,urm;

    while(t[rad] > 0) rad = t[rad];

    while(t[nod] > 0)
    {
        urm = t[nod];
        t[nod] = rad;
        nod = urm;
    }
    return rad;
}

inline void unite(int rx,int ry)
{
    t[ry] = rx;
}

void APM()
{
    int rx,ry;
    while(!coada.empty())
    {
        rx = root(coada.top().second.first);
        ry = root(coada.top().second.second);
        if(rx != ry)
        {
            S += -coada.top().first;
            sol.push_back(make_pair(coada.top().second.first , coada.top().second.second));

            unite(rx,ry);
        }
        coada.pop();
    }
}

int main()
{
    fin>>n>>m;
    for(int i=1; i<=m; ++i)
    {
        fin>>x>>y>>c;
        coada.push(make_pair(-c,make_pair(x,y)));
    }

    APM();

    fout<<S<<"\n"<<n-1<<"\n";

    for(int i=0; i<sol.size(); ++i)
        fout<<sol[i].first<<" "<<sol[i].second<<"\n";

    fin.close(); fout.close();
    return 0;
}