Cod sursa(job #1277784)

Utilizator tatianazTatiana Zapirtan tatianaz Data 28 noiembrie 2014 08:50:19
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream is("dijkstra.in");
ofstream os("dijkstra.out");

#define INF 0x3f3f3f3f

int n, m;
int x, y, cost, nod;

vector <vector <pair <int, int> > > G;
vector <int> D;
queue <int> Q;

int main()
{
    is >> n >> m;
    G.resize(n+1);
    D.resize(n+1);
    for ( int i = 1; i <= m; ++i )
    {
        is >> x >> y >> cost;
        G[x].push_back(make_pair(y, cost));
    }

    for ( int i = 1; i <= n; ++i )
        D[i] = INF;

    Q.push(1);
    D[1] = 0;
    while ( !Q.empty() )
    {
        x = Q.front();
        Q.pop();
        for ( const auto& val : G[x] )
        {
            nod = val.first;
            cost = val.second;
            if ( D[nod] > D[x] + cost )
            {
                D[nod] = D[x] + cost;
                Q.push(nod);
            }
        }
    }

    for ( int i = 2; i <= n; ++i )
    {
        if ( D[i] == INF )
            os << 0 << ' ';
        else
            os << D[i] << ' ';
    }

    is.close();
    os.close();
    return 0;
}