Cod sursa(job #1920139)

Utilizator valentinoMoldovan Rares valentino Data 9 martie 2017 22:37:10
Problema Arbore partial de cost minim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <queue>
#include <fstream>
#include <algorithm>
#include <iostream>
#include <vector>
#define NM 400005
using namespace std;

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

vector < int > sol;
struct muchie
{
    int x, y, c;
};
muchie arb[NM];
int cost, n, gr[NM], ind[NM],m;

bool cmp(const int& i, const int& j)
{
    return arb[ i ].c < arb[ j ].c;
}

int grupa(int i)
{
    while(i != gr[ i ]) i = gr[ i ];
    return gr[ i ];
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        f >> arb[ i ].x >> arb[ i ].y >> arb[ i ].c;
        ind[ i ] = i;
    }
    for(int i = 1; i <= n; ++i) gr[ i ] = i;
    sort(ind + 1, ind + m + 1, cmp);
    for(int i = 1; i <= m; ++i)
    {
        if(grupa( arb[ ind[ i ] ].x ) != grupa( arb[ ind[ i ] ].y ))
        {
            cost += arb[ ind[ i ] ].c;
            gr[ grupa( arb[ ind[ i ] ].x ) ] = grupa( arb[ ind[ i ] ].y );
            sol.push_back(ind[i]);
        }
    }
    g << cost << '\n' << n - 1 << '\n';
    for(int i = 0; i < sol.size(); ++i)
        g << arb[ sol[ i ] ].x << ' ' << arb[ sol[ i ] ].y << '\n';
}