Cod sursa(job #1988814)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 4 iunie 2017 19:35:48
Problema Arbore partial de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <bitset>
#define NMAX 200003
#define oo (1 << 30)

using namespace std;

vector<pair<int, int> > G[NMAX];
int n;
int d[NMAX], father[NMAX];
set<pair<int, int> > heap;
bitset<NMAX> mark;

void read() {

    ifstream in("apm.in");
    int m, x, y, z;
    in >> n >> m;

    for (int i = 1; i <= m; i++) {

        in >> x >> y >> z;
        G[x].push_back(make_pair(y, z));
        G[y].push_back(make_pair(x, z));
    }
    in.close();
}

void apm() {

    int node, where, cost;
    heap.insert(make_pair(0, 1));
    mark.set(1);

    for (int i = 2; i <= n; i++)
        d[i] = oo;

    while (!heap.empty()) {

        node = heap.begin()->second;
        heap.erase(heap.begin());
        mark.set(node);

        for (unsigned int i = 0; i < G[node].size(); i++)
        {
            where = G[node][i].first;
            cost = G[node][i].second;

            if (!mark.test(where) && d[where] > cost)
            {
                if (d[where] != oo)
                    heap.erase(heap.find(make_pair(d[where], where)));

                d[where] = cost;
                father[where] = node;
                heap.insert(make_pair(d[where], where));

            }
        }
    }
}

int main()
{
    read();
    apm();

    long long int cost = 0;

    for (int i = 1; i <= n; i++)
        cost += (d[i] * 1LL);

    ofstream out("apm.out");
    out << cost << "\n";
    out << n - 1 << "\n";

    for (int i = 2; i <= n; i++)
        out << i << " " << father[i] << "\n";

    out.close();
    return 0;
}