Cod sursa(job #865626)

Utilizator cernat.catallinFMI Cernat Catalin Stefan cernat.catallin Data 26 ianuarie 2013 18:22:06
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
#include <vector>
#include <queue>
#include <utility>
#include <list>
using namespace std;

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

#define inf 500000000

typedef pair<unsigned int, unsigned int> pereche;

vector < list<pereche> > graf;
list <pereche>::iterator it;
vector <unsigned int> dist;
vector <bool> vizitat;

struct compare{
    bool operator() (unsigned int i, unsigned int j){
        return dist[i] > dist[j];
    }
};

priority_queue <unsigned int, vector<unsigned int>, compare> coada;
int n, m, start = 1;

void citire(){
    int x, y, c;
    f >> n >> m;

    graf.resize(n+1);
    dist.resize(n+1, inf);
    vizitat.resize(n+1);

    for(int i = 1; i <= m; ++i){
        f >> x >> y >> c;
        graf[x].push_back(pereche(y, c));
    }
    f.close();
}

void dijkstra(){
    unsigned int top;
    coada.push(start);
    dist[start] = 0;

    while(!coada.empty()){
        top = coada.top();
        coada.pop();
        if(!vizitat[top]){
            for(it = graf[top].begin(); it != graf[top].end(); ++it)
                if(dist[it->first] > it->second + dist[top]){
                    dist[it->first] = it->second + dist[top];
                    coada.push(it->first);
                }
            vizitat[top] = true;
        }
    }
}

void afisare(){
    for(int i = 2; i <= n; ++i)
        if(dist[i] == inf) g << "0 ";
            else g << dist[i] << " ";
    g.close();
}

int main(){
    citire();
    dijkstra();
    afisare();
}