Cod sursa(job #3292368)

Utilizator David_Popa123Popa David Matei David_Popa123 Data 8 aprilie 2025 10:10:29
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>

using namespace std;

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

#define MAXN 50000
#define INF 1000000000

struct Nod {
    int to, cost;
};

int d[MAXN + 1];

struct cmp {
    bool operator () ( Nod a, Nod b ) {
        return d[a.to] > d[b.to];
    }
};

vector<Nod> g[MAXN + 1];
priority_queue<Nod, vector<Nod>, cmp> pq;

void dijkstra( int start ) {
    Nod nod;
    d[start] = 0;
    pq.push( { start, 0 } );
    while( !pq.empty() ) {
        nod = pq.top();
        pq.pop();
        if( nod.cost > d[nod.to] )
            continue;
        for( Nod vec : g[nod.to] ) {
            if( d[vec.to] > d[nod.to] + vec.cost ) {
                d[vec.to] = d[nod.to] + vec.cost;
                pq.push( { vec.to, d[vec.to] } );
            }
        }
    }
}

int main() {
    int n, m, i, u, v, cost;

    fin >> n >> m;
    for( i = 1; i <= m; i++ ) {
        fin >> u >> v >> cost;
        g[u].push_back( { v, cost } );
    }

    fill( d + 1, d + n + 1, INF );
    dijkstra( 1 );
    for( i = 2; i <= n; i++ ) {
        if( d[i] == INF )
            fout << 0 << ' ';
        else
            fout << d[i] << ' ';
    }
    return 0;
}