Cod sursa(job #2423556)

Utilizator Earthequak3Mihalcea Cosmin-George Earthequak3 Data 21 mai 2019 18:14:52
Problema Algoritmul lui Dijkstra Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#define inf 1<<30
#define nmax 50005

using namespace std;

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

vector <pair<int, int> > graph[nmax];


int main()
{
    int n,m;
    f>>n>>m;
    vector <int> dist(n+1,inf);
    bool inQueue[n+1];

    for(int i = 1;i<=m;i++)
    {
        int from,to,cost;
        f>>from>>to>>cost;
        graph[from].push_back(make_pair(to, cost));
    }

    dist[1] = 0;
    queue <int> q;
    q.push(1);
    while (!q.empty())
    {
        int nod = q.front();
        inQueue[nod] = false;
        q.pop();
        for(unsigned int i = 0; i< graph[nod].size();i++)
        {
            int to = graph[nod][i].first;
            int cost = graph[nod][i].second;

            if(dist[to] > dist[nod] + cost)
            {
                dist[to] = dist[nod] + cost;
                if(!inQueue[to])
                {
                    inQueue[to] = true;
                    q.push(to);
                }
            }

        }

    }

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


    return 0;
}