Cod sursa(job #1990824)

Utilizator minut1Baies Cosmin minut1 Data 13 iunie 2017 19:58:41
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int N = 50001;
const int INF = 2000001000;
int d[N],pred[N],m,n,c;

priority_queue <pair <int,int> > h;

vector <pair <int,int> > a[N];
bool sel[N];

void citire()
{
    in >> n >> m;
    int x,y;
    for(int i=1; i<=m; i++)
    {
        in >> x >> y >> c;
        a[x].push_back(make_pair(y,c));
    }
}

void dijkstra(int x0)
{
    int x,y;
    for(int i=1; i<=n; i++)
    {
        d[i] = INF;
    }
    d[x0]=0;
    h.push(make_pair(0,x0));
    while(!h.empty())
    {
        while(!h.empty() && sel[h.top().second])
        {
            h.pop();
        }
        if(h.empty())
        {
            return;
        }
        x = h.top().second;
        sel[x] = true;
        for(int i=0; i<a[x].size(); i++)
        {
            y = a[x][i].first;
            c = a[x][i].second;
            if(d[x] + c < d[y])
                d[y] = d[x] + c;
            pred[y] = x;
            h.push(make_pair(-d[y],y));
        }
    }
}

int main()
{
    citire();
    int x0=1;
    dijkstra(x0);
    for(int i=1; i<=n; i++)
        if(i!=x0)
            out << d[i] << " ";
    return 0;
}