Cod sursa(job #2854419)

Utilizator LionMan101Achim-Panescu Silvian LionMan101 Data 21 februarie 2022 13:11:32
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.79 kb
#include <bits/stdc++.h>

using namespace std;

using ll = long long;
const int INF=1e9+7;
const ll INFF=1e18+7;
#define nl '\n'
void __print(int x) { cout << x; }
void __print(long x) { cout << x; }
void __print(long long x) { cout << x; }
void __print(unsigned x) { cout << x; }
void __print(unsigned long x) { cout << x; }
void __print(unsigned long long x) { cout << x; }
void __print(float x) { cout << x; }
void __print(double x) { cout << x; }
void __print(long double x) { cout << x; }
void __print(char x) { cout << '\'' << x << '\''; }
void __print(const char* x) { cout << '\"' << x << '\"'; }
void __print(const string& x) { cout << '\"' << x << '\"'; }
void __print(bool x) { cout << (x ? "true" : "false"); }
template<typename T, typename V>
void __print(const pair<T, V>& x) { cout << '{'; __print(x.first); cout << ','; __print(x.second); cout << '}'; }
template<typename T>
void __print(const T& x) { int f = 0; cout << '{'; for (auto& i : x) cout << (f++ ? "," : ""), __print(i); cout << "}"; }
void _print() { cout << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) { __print(t); if (sizeof...(v)) cout << ", "; _print(v...); }
#ifndef ONLINE_JUDGE
#define debug(x...) cout << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

int n,m;
vector<int> dsu;

int get_root(int x){
    int root=x;
    while(dsu[root]>0){
        root=dsu[root];
    }
    while(x!=root){
        int aux=dsu[x];
        dsu[x]=root;
        x=aux;
    }
    return root;
}

bool join(int x, int y){
    int root1=get_root(x);
    int root2=get_root(y);
    if(root1==root2) return false;
    if(dsu[root1]<=dsu[root2]){
        dsu[root1]+=dsu[root2];
        dsu[root2]=root1;
    }
    else{
        dsu[root2]+=dsu[root1];
        dsu[root1]=root2;
    }
    return true;
}

void solve()
{
    cin>>n>>m;
    vector<tuple<int,int,int>> a;
    dsu.resize(n+1);
    fill(dsu.begin(),dsu.end(),-1);
    for(int i=0; i<m; i++){
        int x,y,c;
        cin>>x>>y>>c;
        a.emplace_back(make_tuple(c,x,y));
    }
    sort(a.begin(),a.end());
    ll sum=0;
    vector<pair<int,int>> ans;
    for(int i=0; i<m; i++){
        int x,y,c;
        tie(c,x,y)=a[i];
        if(join(x,y)){
            sum+=c;
            ans.emplace_back(x,y);
        }
    }
    cout<<sum<<nl;
    for(pair<int,int>& i:ans) cout<<i.first<<" "<<i.second<<nl; 
}

int main()
{
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);

    freopen("apm.in", "r", stdin);
    freopen("apm.out", "w", stdout);

    ios::sync_with_stdio(0);
    cin.tie(0);
    int t=1;
    // int t;
    // cin >> t;
    for(int tt=1; tt<=t; tt++){
        // cout<<"#Case "<<t<<nl;
        solve();
    }
    return 0;
}