Cod sursa(job #2423966)

Utilizator cyber_ghSoltan Gheorghe cyber_gh Data 22 mai 2019 12:43:49
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 200010;

struct node {
    int from, to, dist;
};
int N, M;
vector<node> V;

int parent[MAXN];

bool comp(const node &a, const node &b) {
    return a.dist < b.dist;
}

void init() {
    for (int i = 1; i <= N;i++) parent[i] = i;
}

int root(int el) {
    if (parent[el] == el) return el;
    else return root(parent[el]);
}

void join(int a, int b) {
    int rootA = root(a);
    int rootB = root(b);
    if (rootA != rootB) parent[rootB] = rootA;
}

vector<pair<int,int> > rs;
long long SUM = 0;

int main () {
    ifstream fin("apm.in");
    ofstream cout("apm.out");

    fin >> N >> M;
    init();
    for (int from, to, dist; M--;) {
        fin >> from >> to >> dist;
        V.push_back({from, to, dist});
    }
    sort(V.begin(), V.end(), comp);

    for (auto it: V) {
        if (root(it.from) != root(it.to)) {
            join(it.from, it.to);
            rs.push_back({it.from, it.to});
            SUM += it.dist;
        }
    }

    cout << SUM << endl << rs.size() << endl;
    for (auto it: rs) {
        cout << it.first << " " << it.second << endl;
    }

    return 0;
}