Cod sursa(job #1916186)

Utilizator nartorrewrew narto Data 9 martie 2017 08:11:55
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <algorithm>
#define mmax 400005
#define nmax 200005
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
int n,m,cost,nr;
int t[nmax];
bool ok[nmax];
struct elem {int a;int b;int c;};
elem v[mmax];



bool comp(const elem &p,const elem &q)
{
    return p.c<q.c;
}
int rad(int x)
{
    while (t[x]>0) {
        x=t[x];
    }
    return x;
}

int main()
{
    int i,j,r1,r2;
    f>>n>>m;
    for (i=1;i<=n;i++)
        t[i]=-1;

    for (i=1;i<=m;i++)
        f>>v[i].a>>v[i].b>>v[i].c;

    sort(v+1,v+m+1,comp);

    for (i=1;i<=m;i++) {
        r1=rad(v[i].a);
        r2=rad(v[i].b);

        if (r1!=r2) {
            cost+=v[i].c;
            ok[i]=true;
            nr ++;
            if (nr == n-1)
                break;

            if (t[r1]<t[r2]) {
                t[r1]+=t[r2];
                t[r2]=r1;
            }
            else {
                t[r2]+=t[r1];
                t[r1]=r2;
            }
        }

    }

    g<<cost<<'\n';
    g<<nr<<'\n';
    for (i=1;i<=m;i++)
        if (ok[i]==true)
            g<<v[i].a<<' '<<v[i].b<<'\n';

    return 0;
}