Cod sursa(job #3186607)

Utilizator and_Turcu Andrei and_ Data 23 decembrie 2023 21:17:44
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <bits/stdc++.h>
#define N 50007
using namespace std;

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

int n,m;
vector< pair<int,int> >edges[N];
vector<int> dist(N,-1);
vector<bool> viz(N,0);

void Citire()
{
    fin >> n >> m;
    for(int i=1;i<=m;i++)
    {
        int x,y,c;
        fin >> x >> y >> c;
        edges[x].push_back({c,y});
    }
    fin.close();
}

void Dijkstra()
{
    priority_queue<pair<int,int>> pq;
    pq.push({0,1});
    while( !pq.empty() )
    {
        int x=pq.top().second;
        int c=-pq.top().first;
        pq.pop();
        if( !viz[x] )//  ***
        {
            viz[x]=1;
            dist[x]=c;
            for( auto w:edges[x] )
            {
                int y=w.second;
                int cost= c +w.first;
                if( !viz[y] )  /// ASTA?
                    pq.push({-cost,y});
            }
        }
    }
}

int main()
{
    Citire();
    Dijkstra();
    for(int i=2;i<=n;i++)
        fout << dist[i] << " ";
    fout.close();
    return 0;
}