Mai intai trebuie sa te autentifici.

Cod sursa(job #2492277)

Utilizator IATI2019Iati Shumen IATI2019 Data 14 noiembrie 2019 12:11:37
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>

using namespace std;
vector <pair <int,pair <int,int > > > v;
vector <pair <int,int> > sol;
int boss[200001],nr[200001];
int root(int x){
    if(x == boss[x]){
        return x;
    }
    boss[x] = root(boss[x]);
    return boss[x];
}
void unite(int a,int b){
    a = root(a);
    b = root(b);
    if(nr[a] > nr[b]){
        nr[a] += nr[b];
        boss[b] = a;
    }else{
        nr[b] += nr[a];
        boss[a] = b;
    }
}
int main()
{
    ifstream cin("apm.in");
    ofstream cout("apm.out");
    int i,n,m,sum = 0;
    cin >> n >> m;
    for(i = 1;i <= n;i++)
    {
        boss[i] = i;
        nr[i] = i;
    }
    for(i = 1;i <= m;i++){
        int x,y,z;
        cin >> x >> y >> z;
        v.push_back({z,{x,y}});
    }
    sort(v.begin(),v.end());
    for(auto x : v){
        if(root(x.second.first) != root(x.second.second)){
            sum += x.first;
            sol.push_back({x.second.first,x.second.second});
            unite(x.second.first,x.second.second);
        }
    }
    cout << sum << "\n";
    cout << sol.size() << "\n";
    for(i = 0;i < sol.size();i++){
        cout << sol[i].first << " " << sol[i].second << "\n";
    }
    return 0;
}