Cod sursa(job #3162770)

Utilizator CipriEuCruceanu Ciprian Constantin CipriEu Data 29 octombrie 2023 20:38:33
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include<bits/stdc++.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie{
    int st, dr, val, ok=0;
    muchie(int x, int y, int c){
        st = x, dr = y, val = c;
    }
};
bool cmp(muchie a, muchie b){
    return a.val < b.val;
}
vector<muchie> graf;
int v[200001], cnt=0, sum=0;

int root(int t){
    //cout<<"root "<<t<<"\n";
    if(v[t] == t) return t;
    else{
        v[t] = root(v[t]);
        return v[t];
    }
}
void join(int x, int y){
    //cout<<"--- join "<<x<<" "<<y<<" ----\n";
    int rx = root(x), ry = root(y);
    v[max(rx, ry)] = min(rx, ry);
    //cout<<"--------------------\n";
}

int main(){
    int n, m, x, y, c;
    fin>>n>>m;
    for(int i=1; i<=n; i++) v[i] = i;
    for(int i=1; i<=m; i++){
        fin>>x>>y>>c;
        graf.push_back(muchie(x, y, c));
    }
    sort(graf.begin(), graf.end(), cmp);

    for(int k=0; k<graf.size(); k++){
        x = graf[k].st; y = graf[k].dr; c = graf[k].val;
        int rx = root(x), ry = root(y);
        if(rx != ry){
            join(x, y);
            graf[k].ok = 1;
            cnt++;
            sum += c;
        }
    }
    fout<<sum<<"\n"<<cnt<<"\n";
    for(int k=0; k<graf.size(); k++){
        if(graf[k].ok){
            fout<<graf[k].st<<" "<<graf[k].dr<<"\n";
        }
    }
}