Cod sursa(job #3287014)

Utilizator yawninghorseDragomir Alex yawninghorse Data 14 martie 2025 22:28:49
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int Mmax = 25e4 + 5;
vector <pair<int, int>> lista[Mmax];
int n, m;
const int Nmax = 5e4 + 5;
int dist[Nmax];
bool viz[Nmax];
const int INF = 1e9;

void dijkstra(int node)
{
    for(int i = 1; i <= n; i++)
    {
        dist[i] = INF;
        viz[i] = false;
    }
    dist[node] = 0;
    priority_queue<pair<int, int>> q;
    q.push({0, node});
    while(!q.empty())
    {
        int v = q.top().second;
        q.pop();
        if(viz[v] == true)
        {
            continue;
        }
        else
        {
            viz[v] = true;
            for(int i = 0; i < lista[v].size(); i++)
            {
                int u = lista[v][i].second;
                int cost = lista[v][i].first;
                if(viz[u] == false and dist[u] > cost + dist[v])
                {
                    dist[u] = cost + dist[v];
                    q.push({-dist[u], u});
                }
            }
        }
    }
}

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