Cod sursa(job #2045614)

Utilizator andru47Stefanescu Andru andru47 Data 22 octombrie 2017 16:48:38
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
using namespace std;
int n,m,Sol,ret, t[200005] , rang[200005];
pair <int , pair <int , int> > edge[400005];
pair <int , int> sol[400005];
inline int multime(int nod)
{
    while (nod != t[nod])
        nod = t[nod];
    return nod;
}
inline void unite(pair <int , pair <int , int> > muchie)
{
    int m1 = multime(muchie.second.first);
    int m2 = multime(muchie.second.second);
    if (m1 != m2)
    {
        if (rang[m1] >= rang[m2])
            rang[m1] += (rang[m1] == rang[m2]), t[m2] = m1;
        else t[m1] = m2;
        sol[++Sol] = {muchie.second.first , muchie.second.second};
        ret += muchie.first;
    }
}
int main()
{
    freopen("apm.in" , "r", stdin);
    freopen("apm.out" , "w", stdout);

    scanf("%d %d\n", &n, &m);
    for (int i = 1; i<=m; ++i)
        scanf("%d %d %d", &edge[i].second.first, &edge[i].second.second, &edge[i].first);
    for (int i = 1; i<=n; ++i)
        t[i] = i, rang[i] = 0;
    sort(edge + 1, edge + m + 1);

    for (int i = 1; i<=m; ++i)
        unite(edge[i]);
    printf("%d\n%d\n", ret, Sol);
    for (int i = 1; i<=Sol; ++i)
        printf("%d %d\n", sol[i].first, sol[i].second);
    return 0;
}