Cod sursa(job #2766974)

Utilizator vlad2009Vlad Tutunaru vlad2009 Data 4 august 2021 12:03:55
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int Nmax = 50000;
const long long INF = (1LL << 60);
vector <pair <int, int>> adj[Nmax + 1];
priority_queue <pair <int, int>> q;
bool viz[Nmax + 1];
long long dist[Nmax + 1];
int urm[Nmax + 1];

void Dijkstra()
{
    for (int i = 1; i <= Nmax; i++)
    {
        dist[i] = INF;
    }
    q.push({0, 1});
    dist[1] = 0;
    while (!q.empty())
    {
        int s = q.top().second;
        q.pop();
        if (viz[s])
        {
            continue;
        }
        viz[s] = true;
        for (auto u : adj[s])
        {
            int b = u.first, c = u.second;
            if (dist[s] + c < dist[b])
            {
                dist[b] = dist[s] + c;
                q.push({-dist[b], b});
                urm[b] = s;
            }
        }
    }
}

int main()
{
    ifstream fin("dijkstra.in");
    ofstream fout("dijkstra.out");
    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int u, v, c;
        fin >> u >> v >> c;
        adj[u].push_back({v, c});
    }
    Dijkstra();
    for (int i = 2; i <= n; i++)
    {
        if (dist[i] == INF)
        {
            fout << "0 ";
        }
        else
        {
            fout << dist[i] << " ";
        }
    }
    return 0;
}