Cod sursa(job #1995842)

Utilizator loo_k01Luca Silviu Catalin loo_k01 Data 29 iunie 2017 11:45:00
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>

using namespace std;

struct Triplu
{
    int x, y, c, v;
};

ofstream fout("apm.out");

Triplu a[400002];
int t[200002];
int cnt, n, m;
int sol;


inline bool CMP(const Triplu A, const Triplu B)
{
    return A.c < B.c;
}
void Union(int x, int y)
{
    t[y] = x;
}

int Find(int x)
{
    int rad, y;
    rad = x;
    while(t[rad] != 0)
        rad = t[rad];

    while(x != rad)
    {
        y = t[x];
        t[x] = rad;
        x = y;
    }
    return rad;
}

void Read()
{
    ifstream fin("apm.in");
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> a[i].x >> a[i].y >> a[i].c;
    }
    fin.close();
}

void Solve()
{
    int x,y;
    sort(a + 1, a + m + 1, CMP);

    for(int i = 1; i <= m ; i++)
    {
        x=Find(a[i].x);
        y=Find(a[i].y);
        if(x!=y)
        {
            a[i].v = 1;
            sol += a[i].c;
            Union(x, y);
        }
    }

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

    for(int i = 1; i <= m ; i++)
        if(a[i].v)
            fout << a[i].x << " " << a[i].y << "\n";
}

void Afisare()
{
    int i;
    for(i = 1; i <= m; i++)
        fout << a[i].x << " " << a[i].y << " " << a[i].c << "\n";
}

int main()
{
    Read();
    Solve();
    return 0;
}