Cod sursa(job #2800814)

Utilizator Tudor06MusatTudor Tudor06 Data 14 noiembrie 2021 00:19:11
Problema Algoritmul Bellman-Ford Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <cstring>

using namespace std;

const int NMAX = 5e4;

priority_queue <pair<int,int>> q;
vector <pair<int,int>> edges[NMAX + 1];

int dist[NMAX + 1];
int cnt[NMAX + 1];

int dijkstra( int node, int n ) {
    q.push( {0,node} );

    while ( !q.empty() ) {
        node = q.top().second;
        int d = q.top().first;
        q.pop();

        if ( dist[node] == -1 ) {
            dist[node] = -d;
            for ( auto i : edges[node] ) {
                if ( dist[i.second] == -1 ) {
                    q.push( {d - i.first,i.second} );
                    cnt[i.second] ++;
                    if ( cnt[i.second] == n ) {
                        return 0;
                    }
                }
            }
        }
    }
    return 1;
}
int main() {
    ifstream fin( "bellmanford.in" );
    ofstream fout( "bellmanford.out" );
    int n, i, m, a, b, c;
    fin >> n >> m;
    for ( i = 0; i < m; i ++ ) {
        fin >> a >> b >> c;
        edges[a].push_back( {c,b} );
    }
    memset( dist, -1, sizeof(dist) );
    if ( !dijkstra( 1, n ) ) {
        fout << "Ciclu negativ!";
    } else {
        for ( i = 2; i <= n; i ++ ) {
            fout << dist[i] << ' ';
        }
    }
    return 0;
}