Cod sursa(job #3197439)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 26 ianuarie 2024 20:21:33
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

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

const int DIM = 50010;

int n, m, x, y, c;
int inQueue[DIM], cost[DIM];
vector<pair<int, int>> l[DIM];
queue<pair<int, int>> q;
bool visited[DIM], negativeCicle;

void bellmanford(int start) {
    inQueue[start] = 1;
    visited[start] = true;
    cost[start] = 0;
    q.emplace(start, cost[start]);
    while (!q.empty()) {
        int node = q.front().first;
        visited[node] = false;
        q.pop();

        for (auto adjElem : l[node]) {
            int adjNode = adjElem.first;
            int adjCost = adjElem.second;
            if (cost[adjNode] > cost[node] + adjCost) {
                cost[adjNode] = cost[node] + adjCost;
                if (!visited[adjNode]) {
                    inQueue[adjNode]++;
                    if (inQueue[adjNode] > n) {
                        fout << "Ciclu negativ!";
                        negativeCicle =  true;
                        return;
                    }
                    visited[adjNode] = true;
                    q.emplace(adjNode, cost[adjNode]);
                }
            }
        }
    }
}

int main() {
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        l[x].emplace_back(y, c);
    }

    for (int i = 1; i <= n; i++)
        cost[i] = INT_MAX;
    negativeCicle = false;
    bellmanford(1);

    if (!negativeCicle) {
        for (int i = 2; i <= n; i++)
            fout << cost[i] << ' ';
    }

    return 0;
}