Cod sursa(job #1916615)

Utilizator CraiuAndrei Craiu Craiu Data 9 martie 2017 09:56:51
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nMax = 200005;
int n, m, sol;
int t[nMax], cnt[nMax];
int a[nMax], b[nMax], len;
struct el
{
    int x, y, c;
    bool operator <(const el & A) const
    {
        return c < A.c;
    }
};

el v[2 * nMax];

inline void Read()
{
    int i;
    fin >> n >> m;
    for(i = 1; i <= m; i++)
        fin >> v[i].x >> v[i].y >> v[i].c;
    sort(v + 1, v + 1 + m);
}

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

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

inline void Solve()
{
    int x, y, i, len, ans;
    ans = len = 0;
    for(i = 1; i <= m; i++)
    {
        x = Find(v[i].x);
        y = Find(v[i].y);
        if(x != y)
        {
            Union(x, y);
            ans += v[i].c;
            a[++len] = v[i].x;
            b[len] = v[i].y;
        }
    }
    fout << ans << "\n" << n - 1 << "\n";
    for(i = 1; i < n; i++)
        fout << a[i] << " " << b[i] << "\n";
}

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