Cod sursa(job #1312243)

Utilizator AnesthesicChereches Sergiu Alexandru Anesthesic Data 9 ianuarie 2015 01:03:29
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <fstream>
#include <set>
#include <vector>
using namespace std;
#define nmax 50005
#define inf (1<<30)


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

int n, m, i;
int best[nmax];

vector< pair<int, int> > v[nmax];
set < pair<int, int> > s;

void dijkstra(){
    s.insert(make_pair(1, 0));
    while(!s.empty()){
        int current = s.begin() -> first;
        int minimum = s.begin() -> second;
        s.erase(s.begin());
        for(int i=0; i<v[current].size(); i++){
            if(best[v[current][i].first]>minimum+v[current][i].second){
                best[v[current][i].first] = minimum+v[current][i].second;
                s.insert(make_pair(v[current][i].first, best[v[current][i].first]));
            }
        }
    }
}

int main(){
    int weight, x, y;
    fin >> n >> m;
    for(i=1; i<=m; i++){
        fin >> x >> y >> weight;
        v[x].push_back(make_pair(y, weight));
    }
    for(i=2; i<=n; i++) best[i]= inf;
    dijkstra();

    for(i=2; i<=n; i++)
        if(best[i]==inf)    fout << "0" << " ";
        else    fout << best[i] << " ";
    return 0;
}