Cod sursa(job #2141183)

Utilizator razvan242Zoltan Razvan-Daniel razvan242 Data 24 februarie 2018 10:55:14
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

struct edge {
    int node, cost;
};

struct heapEdge {
    int node, nxt, cost;

    friend bool operator< (heapEdge a, heapEdge b) {
        return a.cost > b.cost;
    }
};

int n, m, root = 1;
vector <bool> viz;
vector <int> t, d;
priority_queue<heapEdge> hp;
vector <vector <edge> > v;

inline void initVectors() {
    viz = vector <bool> (n + 1);
    t = vector <int> (n + 1, -1);
    d = vector <int> (n + 1, 1e9);
    v = vector <vector <edge>> (n + 1);
}

inline void read() {
    fin >> n >> m;

    initVectors();
    int x, y, c;
    for (int i = 1; i <= m; ++i) {
        fin >> x >> y >> c;
        v[x].push_back(edge{y, c});
        v[y].push_back(edge{x, c});
    }
}

inline void solve() {
    t[root] = 0;
    viz[root] = 1;

    for (const auto& ed: v[root])
        hp.push(heapEdge{root, ed.node, ed.cost});

    int cost = 0;
    int x, y, c;
    while (hp.size()) {
        x = hp.top().node;
        y = hp.top().nxt;
        c = hp.top().cost;
        hp.pop();
        if (viz[y])
            continue;

        viz[y] = 1;
        cost += c;
        t[y] = x;
        for (const auto& ed: v[y]) {
            hp.push(heapEdge{y, ed.node, ed.cost});
        }
    }
    fout << cost << '\n';
}

inline void print() {
    fout << n - 1 << '\n';
    for (int i = 2; i <= n; ++i) {
        fout << i << ' ' << t[i] << '\n';
    }
}

int main()
{
    read();
    solve();
    print();

    fin.close();
    fout.close();
    return 0;
}