Cod sursa(job #3290311)

Utilizator Cristian_NegoitaCristian Negoita Cristian_Negoita Data 30 martie 2025 10:50:33
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int NMAX = 50001, INF = 2e9;
vector<pair<int, int>> vec[NMAX];
int vis[NMAX], dist[NMAX], n, m;

void dijkstra(int start)
{
    for(int i = 1; i <= n; i++)
        dist[i] = INF;

    vis[start] = 1, dist[start] = 0;
    priority_queue<pair<int, int>> pq;
    pq.push({start, 0});
    while(!pq.empty())
    {
        int nod = pq.top().first, crt = -pq.top().second;
        pq.pop();
        if(dist[nod] < crt)
            continue;
        for(auto i : vec[nod])
        {
            if(!vis[i.first] || dist[i.first] > dist[nod] + i.second)
            {
                dist[i.first] = dist[nod] + i.second;
                vis[i.first] = 1;
                pq.push({i.first, -dist[i.first]});
            }
        }
    }
}

signed main()
{
    fin >> n >> m;
    while(m--)
    {
        int i, j, cost;
        fin >> i >> j >> cost;
        vec[i].push_back({j, cost});
    }
    dijkstra(1);
    for(int i = 2; i <= n; i++)
        fout << dist[i] << ' ';

    return 0;
}