Cod sursa(job #2425536)

Utilizator CristyXtremeSimion Cristian CristyXtreme Data 24 mai 2019 21:20:25
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int inf = 0x3f3f3f3f;

vector <vector <pair <int, int> > > v(200001);

void prim(int s, int n) {
    vector <int> d(n + 1, inf);
    vector <pair <int, int> > sol;
    vector <int> tata(n + 1, -1);
    vector <bool> sel(n + 1, false);
    priority_queue <pair <int, int>, vector <pair <int, int> >, greater <pair <int, int> > > Q;

    d[s] = 0;
    tata[s] = 0;
    Q.push({0, s});

    long long int cost = 0;
    while (!Q.empty()) {
        auto curent = Q.top();
        int dcurr = curent.first;
        int ncurr = curent.second;
        Q.pop();

        if (d[ncurr] != dcurr)
            continue;

        sol.push_back({ncurr, tata[ncurr]});
        sel[ncurr] = true;
        cost += dcurr;
    
        for (auto muchie : v[ncurr]) {
            int dnext = muchie.first, nnext = muchie.second;
            if (!sel[nnext] && d[nnext] > dnext) {
                d[nnext] = dnext;
                tata[nnext] = ncurr;
                Q.push({d[nnext], nnext});
            }
        }
    }

    sol.erase(sol.begin());

    out << cost << '\n' << sol.size() << '\n';
    for (auto el : sol) {
        out << el.first << ' ' << el.second << '\n';
    }
}

int main() {
    int n, m;
    int a, b, c;

    in >> n >> m;
    for (int i = 0; i < m; i++) {
        in >> a >> b >> c;
        v[a].push_back({c, b});
        v[b].push_back({c, a});
    }

    prim(n, n);

    return 0;
}