Cod sursa(job #2069080)

Utilizator KemyKoTeo Virghi KemyKo Data 18 noiembrie 2017 11:55:21
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 50001
#define INF 1000000000

using namespace std;

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

priority_queue< pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > >h;
vector< pair<int, int> >v[NMAX];
bool w[NMAX];
int d[NMAX];
int n, m;

int main()
{
    int i, a, b, c; //citire
    f>>n>>m;
    for (i=1;i<=m;i++){
        f>>a>>b>>c;
        v[a].push_back(make_pair(c,b));
    }
    for(i=1;i<=n;i++)d[i]=INF;


    int nod;     //rez
    h.push(make_pair(0, 1));
    d[1]=0;
    while(!h.empty()){
        nod = h.top().second;
        h.pop();
        if(w[nod]==false){
            for(i=0;i<v[nod].size();i++){
                if(d[nod] + v[nod][i].first < d[v[nod][i].second]){
                    d[v[nod][i].second] = d[nod] + v[nod][i].first;
                    h.push(make_pair(d[v[nod][i].second], v[nod][i].second));
                }
            }
            w[nod]=true;
        }
    }

    for(int i=2;i<=n;i++){  //afis
        if(d[i]==INF)g<<0<<' ';
        else g<<d[i]<<' ';
    }
return 0;
}