Cod sursa(job #3121469)

Utilizator andrei_marciucMarciuc Andrei andrei_marciuc Data 12 aprilie 2023 21:37:42
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int INF = 1e9 + 9575;
const int MAX = 1e5 + 2;

struct Andrei {
    int nod, cost;

    bool operator<( const Andrei& A ) const {
        return cost > A.cost;
    }
} cur;

std::priority_queue<Andrei> q;
std::vector<Andrei> adj[ MAX ];
int dp[ MAX ];
int n, m, p;

void djs( int nod ) {
    for( int i = 1; i <= n; i++ )
        dp[ i ] = INF;

    dp[ nod ] = 0;
    q.push( { nod, dp[ nod ] } );
    while( !q.empty() ) {
        cur = q.top();
        q.pop();

        for( const Andrei& nxt : adj[ cur.nod ] )
            if( dp[ nxt.nod ] > dp[ cur.nod ] + nxt.cost ) {
                dp[ nxt.nod ] = dp[ cur.nod ] + nxt.cost;
                q.push( { nxt.nod, dp[ nxt.nod ] } );
            }
    }
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    cin >> n >> m;

    while( m-- ) {
        int x, y, cost;
        cin >> x >> y >> cost;

        adj[ x ].push_back( { y, cost } );
    }

    djs( 1 );

    for( int i = 2; i <= n; i++ )
        cout << ( dp[ i ] == INF ? 0 : dp[ i ] ) << ' ';
    cout << '\n';
    return 0;
}