Cod sursa(job #2933131)

Utilizator StanCatalinStanCatalin StanCatalin Data 4 noiembrie 2022 18:04:57
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

const int dim = 50005;

int n, m, dist[dim], nr_muchii[dim];
vector<pair<int,int>> vec[dim];

int BellmanFord() {
    dist[1] = 0;
    queue<int> q;

    q.push(1);

    while (!q.empty()) {
        int x = q.front();
        q.pop();

        if (nr_muchii[x] >= n) return 0;

        for (auto y:vec[x]) {
            if (dist[y.first] > dist[x] + y.second) {
                dist[y.first] = dist[x] + y.second;
                nr_muchii[y.first] = nr_muchii[x] + 1;
                q.push(y.first);
            }
        }
    }
    return 1;
}

int main() {
    in >> n >> m;
    int x, y, cost;
    while (m--) {
        in >> x >> y >> cost;
        vec[x].push_back({y, cost});
    }
    for (int i=1; i<=n; i++) {
        dist[i] = 1e9;
    }
    int rasp = BellmanFord();

    if (rasp == 0) {
        out << "Ciclu negativ!";
    } else {
        for (int i=2; i<=n; i++) {
            out << dist[i] << " ";
        }
    }
    return 0;
}