Cod sursa(job #3284731)

Utilizator rakanDijkstra rakan Data 12 martie 2025 09:40:33
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>
using namespace std;

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

/**
24 12 15 15 19
12 15 15 19
*/

int n, m, dist[50002];
vector<pair <int, int> > G[50002];
priority_queue<pair <int, int > > q;
const int oo = 1e9;
bitset<50002> viz;

void Dijkstra()
{
    for(int i = 1; i <= n; i++)
        dist[i] = oo;
    dist[1] = 0;
    q.push({0, 1});
    while(!q.empty())
    {
        int cost = -q.top().first;
        int nod = q.top().second;
        q.pop();
        if(!viz[nod])
        {
            viz[nod] = true;
            for(auto w : G[nod])
                if(dist[w.first] > cost + w.second)
                {
                    dist[w.first] = cost + w.second;
                    q.push({-dist[w.first], w.first});
                }
        }
    }
}

int main()
{
    int i, j, c;
    fin >> n >> m;
    while(m--)
    {
        fin >> i >> j >> c;
        G[i].push_back({j, c});
    }
    Dijkstra();
    for(i = 2; i <= n; i++)
    {
        if(dist[i] == oo) fout << "0 ";
        else fout << dist[i] << " ";
    }
    return 0;
}