Cod sursa(job #3293461)

Utilizator _andrei4567Stan Andrei _andrei4567 Data 11 aprilie 2025 18:28:50
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream cin ("dijkstra.in");
ofstream cout ("dijkstra.out");

const int INF = 1e9;

const int N = 5e4;
int dist[N + 1];

struct ceva
{
    int nod, cost;
    bool operator < (const ceva & a)const
    {
        return cost > a.cost;
    }
};

vector <pair <int, int> > g[N + 1];

priority_queue <ceva> q;

int n, m, x, y, cost;

void dijkstra (int node)
{
    for (int i = 1; i <= n; ++i)
        dist[i] = INF;
    dist[node] = 0;
    q.push({node, 0});
    while (!q.empty())
    {
        ceva nod = q.top();
        q.pop();
        if (nod.cost > dist[nod.nod])continue;
        for (auto it : g[nod.nod])
            if (dist[it.first] > dist[nod.nod] + it.second)
                dist[it.first] = dist[nod.nod] + it.second, q.push({it.first, dist[it.first]});
    }
}

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        cin >> x >> y >> cost;
        g[x].push_back({y, cost});
    }
    dijkstra (1);
    for (int i = 2; i <= n; ++i)
        if (dist[i] == INF)
            cout << "0 ";
        else
            cout << dist[i] << ' ';
    return 0;
}