Cod sursa(job #2919368)

Utilizator BlueLuca888Girbovan Robert Luca BlueLuca888 Data 17 august 2022 00:57:48
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <bits/stdc++.h>
#pragma GCC optimize ("Ofast")

using namespace std;

ifstream fin  ("apm.in");
ofstream fout ("apm.out");

const int MAX_N = 200005;
const int MAX_M = 400005;

int n, m, total;
struct edge{
    int nod1;
    int nod2;
    int cost;

    inline bool operator < (const edge &rhs) const{
        return cost < rhs.cost;
    }

}input; vector <edge> e, sol;


int parent[MAX_N];
static inline int root(int nod){
    int rad = nod;
    while(parent[rad])
        rad = parent[rad];

    int cpy;
    while(parent[nod]){
        cpy = nod;
        nod = parent[nod];
        parent[cpy] = rad;
    }

    return rad;
}

static inline void join(const int &x, const int &y){
    int rx = root(x);
    int ry = root(y);
    if(rx != ry)
        parent[rx] = ry;
}

static inline bool query(const int &x, const int &y){
    int rx = root(x);
    int ry = root(y);
    return rx == ry;
}

int main (){
    ios_base::sync_with_stdio(false);
    fin.tie(nullptr), fout.tie(nullptr);

    fin>>n>>m;
    for(int i=1; i<=m; i++){
        fin>>input.nod1>>input.nod2>>input.cost;
        e.emplace_back(input);
    }

    sort(e.begin(), e.end());

    for(int i=0; i < m; i++){
        if(!query(e[i].nod1, e[i].nod2)){ /// nu sunt in ac comp conexa
            join(e[i].nod1, e[i].nod2);
            total += e[i].cost;
            sol.emplace_back(e[i]);
        }
    }

    fout<<total<<"\n"<<(int)sol.size()<<"\n";
    for(auto output : sol)
        fout<<output.nod1<<" "<<output.nod2<<"\n";
    return 0;
}