Cod sursa(job #2423610)

Utilizator Earthequak3Mihalcea Cosmin-George Earthequak3 Data 21 mai 2019 18:50:44
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <cassert>
#include <algorithm>
#include <cstring>


using namespace std;
const int nmax = 50005;
const int inf = 0x3f3f3f3f;

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

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

    bool inQueue[nmax];


int main()
{
    int n,m;
    f>>n>>m;
    assert(1 <= n && n <= 50000);
    assert(1 <= m && m <= 250000);
    memset(dist, inf, sizeof dist);

    for(int i = 1;i<=m;i++)
    {
        int from,to,cost;
        f>>from>>to>>cost;
        assert(1 <= from && from <= n);
        assert(1 <= to && to <= n);
        assert(0 <= cost && cost <= 20000);
        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(vector<pair<int, int> >::iterator it = graph[nod].begin(); it != graph[nod].end(); ++it)
        {
            int to = it->first;
            int cost = it->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]<<" ";
    }
    f.close();
    g.close();

    return 0;
}