Cod sursa(job #3005620)

Utilizator CalinHanguCalinHangu CalinHangu Data 17 martie 2023 09:44:29
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>

#define ll long long
#define pb push_back
#define pii pair<int, int>
#define x first
#define y second

using namespace std;

ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

const int NMAX = 50005;
const int INF = 1e9 + 7;
const char nl = '\n';

int n, m, f[NMAX], dist[NMAX];
bool cycle = false;

vector<pii> v[NMAX];

queue<pii> q;

void blf(int source){
    for(int i = 1; i <= n; ++i)
        dist[i] = INF;
    f[source] = 1, dist[source] = 0;
    q.push({source, 0});

    while(!q.empty()){
        int cur_node = q.front().x;
        int cur_weight = q.front().y;
        q.pop();
        if(f[cur_node] == n - 1){
            cycle = true;
            return;
        }
        for(auto neigh: v[cur_node]){
            if(dist[neigh.x] > dist[cur_node] + neigh.y){
               dist[neigh.x] = dist[cur_node] + neigh.y;
               q.push({neigh.x, dist[neigh.x]});
               f[neigh.x]++;
            }
        }
    }
}

int main()
{
    in >> n >> m;
    for(int i = 1; i <= m; ++i){
        int a, b, w;
        in >> a >> b >> w;
        v[a].pb({b, w});
        //v[b].pb({a, w});
    }
    blf(1);
    if(cycle == true)
        out << "Ciclu negativ!" << nl;
    else{
        for(int i = 2; i <= n; ++i)
            out << dist[i] << ' ';
        out << nl;
    }
    return 0;
}