Cod sursa(job #3208701)

Utilizator devilexeHosu George-Bogdan devilexe Data 29 februarie 2024 12:45:45
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MAXN = 200'000;
int dag_root[MAXN + 1], dag_depth[MAXN + 1], dag_edges = 0;
int N, M;
vector<tuple<int,int,int> > edges;
vector<pair<int,int> > sol;
int cost;

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

void read() {
    fin >> N >> M;
    init();
    int a, b, c;
    while(M--) {
        fin >> a >> b >> c;
        edges.emplace_back(c, a, b);
    }
    sort(edges.begin(), edges.end(), std::less<tuple<int,int,int> >());
}

int dag_getRoot(int x) {
    if(dag_root[x] == x)
        return x;
    return (dag_root[x] = dag_getRoot(dag_root[x]));
}

bool dag_unit(int x, int y) {
    int rootX = dag_getRoot(x), rootY = dag_getRoot(y);
    if(rootX == rootY) return false;
    ++dag_edges;
    sol.emplace_back(x, y);
    if(dag_depth[rootX] <= dag_depth[rootY]) {
        dag_root[rootX] = rootY;
        if (dag_depth[rootX] == dag_depth[rootY])
            ++dag_depth[rootY];
    } else {
        dag_root[rootY] = rootX;
    }
    return true;
}

void solve() {
    int i = 0, a, b, c;
    while(dag_edges != N - 1)
    {
        tie(c, a, b) = edges[i++];
        if (dag_unit(a, b))
            cost += c;
    }
}

void print() {
    fout << cost << '\n';
    fout << N - 1 << '\n';
    int a, b;
    for(const auto& x : sol) {
        tie(a, b) = x;
        fout << a << ' ' << b << '\n';
    }
}

int main()
{
    read();
    solve();
    print();
    fin.close();
    fout.close();
    return 0;
}