Cod sursa(job #3151270)

Utilizator Paul281881818818181991919191881818Draghici Paul Paul281881818818181991919191881818 Data 20 septembrie 2023 15:37:34
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <vector>
#include <queue>
std::ifstream fin("bellmanford.in");
std::ofstream fout("bellmanford.out");
#define INF (1 << 30) - 1
std::vector<std::vector<std::pair<int, int>>> V;
std::vector<int> dist, viz;
int main(){
    int n, m;
    fin >> n >> m;
    V = std::vector<std::vector<std::pair<int, int>>> (n + 1);
    dist = viz = std::vector<int> (n + 1);
    for(int i = 1; i <= m; ++i){
        int x, y, c;
        fin >> x >> y >> c;
        V[x].push_back({y, c});
    }
    dist[1] = 0;
    for(int j = 2; j <= n; j++)
        dist[j] = INF;
    std::queue<int> Q;
    Q.push(1);
    viz[1] = 1;
    int ok = 1;
    while(!Q.empty()){
        int node = Q.front();
        Q.pop();
        if(ok == 0) break;
        for(std::pair<int, int> it : V[node]){
            if(dist[it.first] > dist[node] + it.second){
                viz[it.first] ++;
                if(viz[it.first] >= n)
                    ok = 0;
                dist[it.first] = dist[node] + it.second;
                Q.push(it.first);
            }
        }
    }
    if(ok == 0)
        fout << "Ciclu negativ!";
    else{
        for(int i = 2; i <= n; i++){
            if(dist[i] == INF) 
                fout << 0 << " ";
            else
                fout << dist[i] << " ";
        }
    }
}