Cod sursa(job #2238010)

Utilizator sorynsooSorin Soo sorynsoo Data 4 septembrie 2018 11:10:54
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;
ifstream fin("bellmanford.in");
ifstream fout("bellmanford.out");

#define MAXN 50005
#define INF 0x3f3f3f3f

struct Node {
    int node;
    int cost;
};

vector<Node> graf[MAXN];
int costUntil[MAXN];
int timesVisited[MAXN];

int main() {
    int n, m;
    fin >> n >> m;

    // Citire
    for(int i = 1; i <= m; i++) {
        int x;
        Node crt;

        fin >> x >> crt.node >> crt.cost;
        graf[x].push_back(crt);
    }

    for(int i = 1; i<= n; i++)
        costUntil[i] = INF;

    queue<int> q;
    q.push(1);
    costUntil[1] = 0;

    bool negativeCycle = false;
    while(!negativeCycle && !q.empty()) {
        int crtNode = q.front(); q.pop();

        for(int i = 0 ; i < graf[crtNode].size(); i++) {
            Node nextNode = graf[crtNode][i];

            if(costUntil[nextNode.node] > costUntil[crtNode] + nextNode.cost) {
                timesVisited[nextNode.node]++;
                if(timesVisited[nextNode.node] > n) {
                    negativeCycle = true;
                }

                costUntil[nextNode.node] = costUntil[crtNode] + nextNode.cost;
                q.push(nextNode.node);
            }
        }
    }

    if(negativeCycle) {
        cout << "Ciclu negativ!";
    } else {
        for(int i = 2; i <= n; i++) {
            cout << costUntil[i] << " ";
        }
    }
    
    return 0;
}