Cod sursa(job #3130272)

Utilizator TODEToderita Mihai TODE Data 17 mai 2023 13:58:59
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const long long N = 5e4 , INF = 1e9;
int n , m , dist[N + 1];
vector<pair<int , int> > v[N + 1];
queue<int> q;
bool bellman(int x){
    int starting_point = x , n_added_to_q[N + 1];
    dist[x] = 0;
    q.push(x);
    n_added_to_q[x]++;
    while(!q.empty()){
        int j = q.front();
        q.pop();
        for(int y = 0 ; y < v[j].size() ; ++y){
            int neigh = v[j][y].first , dist_to_neigh = v[j][y].second;
            if(dist[j] + dist_to_neigh < dist[neigh]){
                n_added_to_q[neigh]++;
                dist[neigh] = dist[j] + dist_to_neigh;
                if(n_added_to_q[neigh] == n){
                    return false;
                }
                if(neigh != starting_point){
                    q.push(neigh);
                }
            }
        }
    }
    return true;
}
void afis(){
    for(int i = 2 ; i <= n ; i++){
        out << dist[i] << ' ';
    }
}

int main(){
    in >> n >> m;
    for(int i = 1 ; i <= m ; ++i){
        int x , y , w;
        in >> x >> y >> w;
        v[x].push_back({y , w});
    }
    for(int i = 1 ; i <= n ; ++i){
        dist[i] = INF;
    }
    if(!bellman(1)){
        out << "Ciclu negativ!";
    }
    else{
        afis();
    }

}