Cod sursa(job #1437748)

Utilizator armandpredaPreda Armand armandpreda Data 18 mai 2015 15:33:15
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>
#include <algorithm>
#include <bitset>

using namespace std;

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

const int LIM=400005, LIM2=200005;
int n, m, p[LIM2], h[LIM2];
struct muc
{
    int x, y, c;
}v[LIM];
bitset <LIM2> viz;
bool cmp(muc a, muc b)
{
    return a.c<b.c;
}
int find_tata(int x)
{
        if(x==p[x])
            return x;
        p[x]=find_tata(p[x]);
        return p[x];
}
void unific(int x, int y)
{
    if(h[x]==h[y])
        p[y]=x, h[x]++;
    if(h[x]>h[y])
        p[y]=x;
    if(h[x]<h[y])
        p[x]=y;
}
int main()
{
    fin>>n>>m;
    for(int i=1; i<=m; ++i)
        fin>>v[i].x>>v[i].y>>v[i].c;
    sort(v+1, v+m+1, cmp);
    for(int i=1; i<=n; ++i)
        p[i]=i;
    int sol=0, nr=0;
    for(int i=1; i<=m; ++i)
    {
        int tx=find_tata(v[i].x), ty=find_tata(v[i].y);
        if(tx!=ty)
        {
            sol+=v[i].c;
            nr++;
            viz[i]=1;
            unific(tx, ty);
        }
    }
   fout<<sol<<'\n'<<nr<<'\n';
    for(int i=1; i<=m; ++i)
        if(viz[i])
            fout<<v[i].x<<' '<<v[i].y<<'\n';
    return 0;
}