Cod sursa(job #1712803)

Utilizator antanaAntonia Boca antana Data 3 iunie 2016 19:08:42
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <cstdio>
#include<algorithm>
#define MAXN 200000
#define MAXM 400000
using namespace std;
struct muchie{
    int cost, x, y;
}v[MAXM+1], rasp[MAXN];
bool cresc(const muchie a, const muchie b)
{
    if(a.cost<b.cost)
        return true;
    return false;
}
int t[MAXN+1];
int father(int x)
{
    if(t[x]==x)
        return x;
    return t[x]=father(t[x]);
}
inline void join(int x, int y)
{
    int rx=father(x), ry=father(y);
    t[rx]=ry;
}
int main()
{
    freopen("apm.in", "r", stdin);
    freopen("apm.out", "w", stdout);
    int n, m, nr=0, c=0;
    scanf("%d%d", &n, &m);
    for(int i=1;i<=m;++i)
        scanf("%d%d%d", &v[i].x, &v[i].y, &v[i].cost);
    sort(v+1, v+m+1, cresc);
    for(int i=1;i<=n;++i)
        t[i]=i;
    for(int i=1;i<=m && nr<n-1; ++i)
    {
        if(t[father(v[i].x)]!=t[father(v[i].y)]){
            c+=v[i].cost;
            nr++;
            rasp[nr]=v[i];
            join(v[i].x, v[i].y);
        }
    }
    printf("%d\n%d\n", c, nr);
    for(int i=1;i<=nr;++i)
        printf("%d %d\n", rasp[i].x, rasp[i].y);
    return 0;
}