Cod sursa(job #2908028)

Utilizator minecraft3Vintila Valentin Ioan minecraft3 Data 1 iunie 2022 10:14:11
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 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]++;
                if(checked[it.first] == n){
                    g << "Ciclu negativ!\n";
                    return 0;
                }
            }
        }
    }
    for(int i = 2 ; i <= n ; i++)
        g << dist[i] << " ";
    return 0;
}