Cod sursa(job #2162173)

Utilizator CraiuAndrei Craiu Craiu Data 12 martie 2018 08:41:24
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nMax = 200005;
int N, M, ans, top;
int t[nMax], a[nMax], b[nMax];
struct el
{
    int x, y, cost;
    bool operator <(const el &A)const
    {
        return cost < A.cost;
    }
};
el v[nMax];

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 Read()
{
    fin >> N >> M;
    for(int i = 1; i <= M; i++)
        fin >> v[i].x >> v[i].y >> v[i].cost;
    sort(v + 1, v + 1 + M);
}

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

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