Cod sursa(job #2966089)

Utilizator Roman70Maruseac Roman Roman70 Data 16 ianuarie 2023 19:00:41
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include "bits/stdc++.h" 
#define ll long long
using namespace std;


bool CASES = 0;
 
#define       forn(i,n)              for(int i=0;i<n;i++)
#define          all(v)              v.begin(), v.end()
#define         rall(v)              v.rbegin(),v.rend()
 
#define            pb                push_back
#define          sz(a)               (int)a.size()
const int MX = 400005;
int n,m;
int k, sum;
int TT[MX], RG[MX];
pair<int,int>P[MX];
struct Muchie{
    int x,y,cost;
} V[MX];
int find(int nod){
    while(TT[nod] != nod)
        nod = TT[nod];
    return nod;
}
bool compare(Muchie a, Muchie b){
    return a.cost < b.cost;
}
void combine(int x, int y){
    if(RG[x] > RG[y])
    TT[y] = x;
    else if(RG[y] > RG[x]) TT[x] = y;
    else{
        TT[x] = y;
        RG[y]++;
    }
}
void solve(){
    
    int n,m;
    cin >> n >> m;
    for(int i = 1;i<=m;i++){
        cin >> V[i].x >> V[i].y >> V[i].cost;
    }
    sort(V+1,V+m+1,compare);
    for(int i = 1;i<=m;i++){
        TT[i] = i;
        RG[i] = 1;
    }
    for(int i = 1;i<=m;i++){
        int tata_x = find(V[i].x);
        int tata_y = find(V[i].y);
        if(tata_x != tata_y){
            combine(tata_x,tata_y);
            P[++k].first = V[i].x;
            P[k].second = V[i].y;
            sum += V[i].cost;
        }

    }
    cout<<sum<<"\n"<<k<<"\n";
    for(int i = 1;i<=k;i++){
        cout<<P[i].first<<" "<<P[i].second<<"\n";
    }

    
     









}


int main(){
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    freopen("apm.in","r",stdin);
    freopen("apm.out","w",stdout);
    int t = 1;
    if(CASES)cin >> t;
    while(t--) solve();

    return 0;
}