Cod sursa(job #2907314)

Utilizator bluestorm57Vasile T bluestorm57 Data 29 mai 2022 17:53:06
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX= 5e4 + 10;
const int inf = 1e9;
int n,m,dist[NMAX], checked[NMAX];
vector < pair < int, int > > v[NMAX];

int main(){
    f >> n >> m;
    for(int i = 0 ; i < m ; i++){
        int x, y, z;
        f >> x >> y >> z;
        v[x].push_back({y,z});
    }

    for(int i = 2 ; i <= n ; i++)
        dist[i] = inf;

    deque < int > q;
    q.push_back(1);
    while(!q.empty()){
        int node = q.front();
        q.pop_front();

        for(auto it: v[node]){
            if(dist[it.first] > dist[node] + it.second){
                dist[it.first] = dist[node] + it.second;
                q.push_back(it.first);

                checked[it.first] = checked[node] + 1;
                if(checked[it.first] > n + 2){
                    g << "Ciclu negativ!\n";
                    return 0;
                }
            }
        }
    }

    for(int i = 2 ; i <= n ; i++)
        g << dist[i] << " ";

    return 0;
}