Cod sursa(job #1628403)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 3 martie 2016 23:58:22
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define oo 1<<30

using namespace std;

ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
const int NMAX = 50001;
vector<pair<int,int> > muchii[NMAX];
queue<int> coada;
int values[NMAX];
int n,m;

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

void bellman()
{
      for(int i=2;i<=n;i++)
        values[i] = oo;
    coada.push(1);
    int y,target,cost;
    while(!coada.empty())
    {
        y = coada.front();
        for(unsigned int i= 0;i<muchii[y].size();i++)
        {
            target = muchii[y][i].first;
            cost = muchii[y][i].second;
            if(values[target] > values[y] + cost)
            {
                values[target] = values[y] + cost;
               coada.push(target);
            }
        }
    coada.pop();
    }
}

int main()
{
    citire();
    bellman();
    for(int i=2;i<=n;i++)
        if(values[i]==oo)
        out<<0<<" ";
    else
        out<<values[i]<<" ";
    out.close();
    return 0;
}