Cod sursa(job #2425566)

Utilizator diliriciraduDilirici Radu diliriciradu Data 24 mai 2019 21:42:09
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define inf 100000
#define Nmax 50005

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

int viz[Nmax];
int dist[Nmax];
vector <pair <int, int>> v[Nmax];
priority_queue <pair <int, int>> Q;

int main()
{
    int n, m;
    int x, y, c;
    fin>>n>>m;
    for (int i = 0; i < m; i++)
    {
        fin>>x>>y>>c;
        v[x].push_back({c, y});
    }

    for (int i = 0; i <= n; i++)
        dist[i] = inf;

    dist[1] = 0;
    Q.push({0, 1});

    while (!Q.empty())
    {
        int nod = Q.top().second;
        Q.pop();

        if (viz[nod])
            continue;
        vector <pair <int, int>>::iterator it;
        for (it = v[nod].begin(); it != v[nod].end(); it++)
            if (dist[it->second] > dist[nod] + it->first)
            {
                dist[it->second] = dist[nod] + it->first;
                Q.push({-dist[it->second], it->second});
            }
        viz[nod] = 1;
    }

    for (int i = 2; i <= n; i++)
        if (dist[i] < inf)
            fout<<dist[i]<<" ";
        else
            fout<<"0 ";

    return 0;
}