Cod sursa(job #2209881)

Utilizator GeorgianBaditaBadita Marin-Georgian GeorgianBadita Data 4 iunie 2018 22:53:14
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include<fstream>
#include<vector>
#include<queue>
#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} {}

};

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

void read_data(){
    f >> n >> m;
    for(int i = 1; i<=m; i++){
        int x, y, c;
        f >> x >> y >> c;
        G[x].push_back({y, c});
    }
}

void bellman(int src){
    queue<int> q;
    int neg_cyc[n + 1];
    for(int i = 1; i<=n; i++){
        dist[i] = INF;
        neg_cyc[i] = 0;
    }
    dist[src] = 0;
    q.push(src);
    while(!q.empty()){
        int nod = q.front();
        q.pop();
        for(const auto& adj: G[nod]){
            if(dist[nod] + adj.cost < dist[adj.y]){
                dist[adj.y] = dist[nod] + adj.cost;
                if(neg_cyc[adj.y] > n){
                    negative = true;
                    return;
                }
                else{
                    neg_cyc[adj.y] ++;
                    q.push(adj.y);
                }
            }
        }
    }
}

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


int main(){
    read_data();
    print_sol();
    return 0;
}