Cod sursa(job #2145384)

Utilizator tanasaradutanasaradu tanasaradu Data 27 februarie 2018 12:30:58
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("apm.in");
ofstream fout ("apm.out");
const int Nmax = 200005;
struct T
{
    int x , y , cost;
    bool reset;
};
T a[Nmax];
int n , m , t[Nmax];
inline bool CMP(const T A , const T B)
{
    return A . cost < B . cost;
}
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 x;
}
int main()
{
    int sum = 0;
    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++)
    {
        int x , y;
        x = Find(a[i] . x);
        y = Find(a[i] . y);
        if(x != y)
        {
            sum += a[i] . cost;
            a[i] . reset = true;
            Union(x , y);
        }
    }
    fout << sum << "\n" << n - 1 << "\n";
    for(int i = 1 ; i <= m ; i++)
        if(a[i] . reset)
            fout << a[i] . x << " " << a[i] . y << "\n";
    fin.close();
    fout.close();
    return 0;
}