Cod sursa(job #2366956)

Utilizator qwerty1234qwerty qwerty1234 Data 4 martie 2019 23:20:24
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb

#include <bits/stdc++.h>


using namespace std;

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

const int Nmax = 200005;

int n , m , t[Nmax] , ans;

struct G
{
    int x , y , cost;
    bool ok;
};

G a[2 * Nmax];

inline void Union(int x , int y)
{
    t[y] = x;
}

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

inline bool CMP(const G A , const G B)
{
    return A.cost < B.cost;
}

int main()
{
    int x , y;
    fin >> n >> m;
    for(int i = 1 ; i <= m ; i++)
        fin >> a[i].x >> a[i].y >> a[i].cost;
    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)
        {
            ans += a[i].cost;
            a[i].ok = true;
            Union(x , y);
        }
    }
    fout << ans << "\n";
    fout << n - 1 << "\n";
    for(int i = 1 ; i <= m ; i++)
        if(a[i].ok)
            fout << a[i].x << " " << a[i].y << '\n';
    fin.close();
    fout.close();
}