Cod sursa(job #1114019)

Utilizator rares96cheseliRares Cheseli rares96cheseli Data 21 februarie 2014 10:26:01
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");

int N, M, GR[200002], sol[200002], cost, K;
struct muchie{ int x, y, c; }m[400002];
struct cmp
{
    bool operator()(const muchie &A, const muchie &B)const
    {
        if (A.c<B.c) return 1;
        return 0;
    }
};

int grupa(int nod)
{
    if (GR[nod]==nod) return nod;
    GR[nod]=grupa(GR[nod]);
    return GR[nod];
}

void uneste(int x, int y) { GR[grupa(x)]=grupa(y); }

int main()
{
    f>>N>>M;
    for (int i=1; i<=M; ++i)
        f>>m[i].x>>m[i].y>>m[i].c;
    for(int i=1; i<=N; ++i)
        GR[i]=i;
    sort(m+1, m+M+1, cmp());

    for (int i=1; i<=M && K!=N-1; ++i)
        if (grupa(m[i].x)!=grupa(m[i].y))
        {
            cost+=m[i].c; sol[++K]=i;
            uneste(m[i].x, m[i].y);
        }

    g<<cost<<'\n'<<K<<'\n';
    for (int i=1; i<N; ++i)
        g<<m[sol[i]].x<<' '<<m[sol[i]].y<<'\n';
    return 0;
}