Cod sursa(job #2070028)

Utilizator giotoPopescu Ioan gioto Data 19 noiembrie 2017 10:24:29
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
using namespace std;

int n, m;
int TT[200005], RG[200005];
vector <pair <int, int> > v;
struct V{
    int x, y, c;
    bool operator < (const V &aux)const{
        return c < aux.c;
    }
};
V a[400005];
inline int find(int x){
    int R;
    for(R = TT[x]; TT[R] != R ; R = TT[R]) ;
    while(x != TT[x]){
        int y = TT[x];
        TT[x] = R;
        x = y;
    }
    return TT[x];
}
inline void unire(int x, int y){
    if(RG[x] > RG[y]) TT[y] = x;
    else if(RG[y] < RG[x]) TT[x] = y;
    else{
        ++RG[y];
        TT[x] = y;
    }
}
int main()
{
    freopen("apm.in", "r", stdin);
    freopen("apm.out", "w", stdout);
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= m ; ++i)
        scanf("%d%d%d", &a[i].x, &a[i].y, &a[i].c);
    for(int i = 1;  i<= n ; ++i){
        TT[i] = i; RG[i] = 1;
    }
    sort(a + 1, a + m + 1);
    int Sol = 0, cnt = 0;
    for(int i = 1; i <= m ; ++i)
        if(find(a[i].x) != find(a[i].y)){
            Sol += a[i].c, unire(find(a[i].x), find(a[i].y));
            ++cnt; v.push_back(make_pair(a[i].x, a[i].y));
        }
    printf("%d\n%d\n", Sol, cnt);
    for(vector <pair <int, int> > :: iterator it = v.begin() ; it != v.end() ; ++it)
        printf("%d %d\n", it->first, it->second);
    return 0;
}