Cod sursa(job #2756300)

Utilizator filicriFilip Crisan filicri Data 30 mai 2021 18:00:26
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <vector>
#include <climits>
#include <queue>
#define N_MAX 50001

using namespace std;

int main() {
    ifstream f("bellmanford.in");
    int n, m;
    vector<pair<int, int>> G[N_MAX];
    f >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y, c;
        f >> x >> y >> c;
        G[x].push_back({y, c});
    }
    f.close();

    int dist[n + 1], fr[n + 1];
    dist[1] = fr[1] = 0;
    for (int i = 2; i <= n; i++) {
        dist[i] = INT_MAX;
        fr[i] = 0;
    }

    bool found = false;
    queue<int> q;
    q.push(1);
    while (!q.empty() && !found) {
        int node = q.front();
        q.pop();
        for (const auto& ne: G[node]) {
            if (fr[ne.first] < n && dist[ne.first] > dist[node] + ne.second) {
                dist[ne.first] = dist[node] + ne.second;
                fr[ne.first]++;
                q.push(ne.first);
            }
            else if (fr[ne.first] >= n)
                found = true;
        }
    }

    ofstream g("bellmanford.out");
    if (found)
        g << "Ciclu negativ!";
    else {
        for (int i = 2; i <= n; i++)
            g << dist[i] << ' ';
    }
    g.close();
    return 0;
}