Cod sursa(job #724705)

Utilizator vendettaSalajan Razvan vendetta Data 26 martie 2012 18:57:57
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <vector>
#include <queue>
#define inf (1<<30)
#define nmax 50005

using namespace std;

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

int n, m, d[nmax];
vector<pair<int, int> > gf[nmax];

void citeste(){

    f >> n >> m;
    for(int i=1; i<=m; i++){
        int x, y, z;
        f >> x >> y >> z;
        gf[x].push_back(make_pair(y,z));
    }

}

struct cmp{

    bool operator() (int a, int b){
        return d[a] < d[b];
    }

};

void rezolva(){

    for(int i=1; i<=n; i++) d[i] = inf;

    d[1] = 0;

    priority_queue<int,vector<int>, cmp> Q;
    Q.push(1);

    for(; Q.size(); ){
        int nod = Q.top();
        Q.pop();
        for(int i=0; i<gf[nod].size(); i++){
            int vc = gf[nod][i].first;
            int cost = gf[nod][i].second;
            if (d[vc] > d[nod] + cost){
                d[vc] = d[nod] + cost;
                Q.push(vc);
            }
        }
    }

}

void scrie(){

    for(int i=2; i<=n; i++){
        if (d[i] == (1<<30)) g << 0 << " ";
        else g << d[i] << " ";
    }

}

int main(){

    citeste();
    rezolva();
    scrie();

    f.close();
    g.close();

    return 0;

}