Cod sursa(job #2203978)

Utilizator GeorgianBaditaBadita Marin-Georgian GeorgianBadita Data 13 mai 2018 22:00:40
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <queue>
#include <vector>
#define pb push_back
#define NMAX 50005
#define INF 1e9

using namespace std;

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

struct Node{
    int y, cost;
    Node(int y, int cost): y{y}, cost{cost}{}
};

queue<int> q;
vector<Node>G[NMAX];
bool is_negative = false;
int dist[NMAX];
int n, m;

void read_data(){
    f >> n >> m;
    for(int i = 1; i<=m; i++){
        int x, y , cost;
        f >> x >> y >> cost;

        G[x].pb({y, cost});
    }
}

void bellman(int src){
    int neg_cycle[NMAX];
    for(int i = 1; i<=n; i++){
        dist[i] = INF;
        neg_cycle[i] = 0;
    }
    dist[src] = 0;
    q.push(src);
    while(!q.empty()){
        int node = q.front();
        q.pop();
        for(int i = 0; i<G[node].size(); i++){
            auto neigh = G[node][i];
            if(dist[neigh.y] >  dist[node] + neigh.cost){
                dist[neigh.y] =  dist[node] + neigh.cost;
                neg_cycle[neigh.y] ++;
                if(neg_cycle[neigh.y] > n){
                    is_negative = true;
                    return;
                }else{
                    q.push(neigh.y);
                }
            }
        }
    }
}

int main(){
    read_data();
    bellman(1);
    if(is_negative == true){
        g << "Ciclu negativ!";
    }else{
        for(int i = 2; i<=n; i++){
            dist[i] != INF ? g << dist[i] << ' ' : g << 0 << ' ';
        }
    }
    return 0;
}