Cod sursa(job #1323486)

Utilizator rockerboyHutter Vince rockerboy Data 21 ianuarie 2015 09:02:14
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <vector>
#include <queue>
#include <list>
#include <climits>

#define NODE(n) (n>>10)
#define COST(n) (n&1023)

std::ifstream in ("dijkstra.in");
std::ofstream out ("dijkstra.out");

int n, m;
std::vector< std::list<int> > x;
std::vector<int> path;



std::priority_queue<int, std::vector<int>, std::less<int> > Min;
void dijkstra (int node)
{
    path[node] = 0;
    Min.push (node);

    int pos, newlen;
    std::list<int>::iterator i;
    while (Min.size()) {
        pos = Min.top(); Min.pop();
        for (i=x[pos].begin(); i!=x[pos].end(); i++) {
            newlen = path[pos] + COST(*i);
            if (newlen < path[NODE(*i)]) {
                path[NODE(*i)] = newlen;
                Min.push (NODE(*i));
            }
        }
    }
}

int main()
{
    in >> n >> m;
    x.resize (n+1);
    path.resize (n+1, INT_MAX);

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

    dijkstra (1);

    for (i=2; i<=n; i++) {
        if (path[i] != INT_MAX) out << path[i] << " ";
        else out << "0 ";
    }
}