Cod sursa(job #2964731)

Utilizator Chiri_Robert Chiributa Chiri_ Data 13 ianuarie 2023 19:57:52
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m, x, y, z;
vector<pair<int, int>> g[50001];
vector<int> dist(50001, INT_MAX), nr(50001);
queue<int> q;
bool viz[50001];

bool bellmanford() {
    q.push(1);
    dist[1] = 0;

    while (!q.empty()) {
        int t = q.front();
        q.pop();
        viz[t] = 0;

        for (auto& x : g[t]) {
            if (dist[x.first] > dist[t] + x.second) {
                nr[x.first]++;
                if (nr[x.first] > n) {
                    return 0;
                }

                dist[x.first] = dist[t] + x.second;

                if (!viz[x.first]) {
                    q.push(x.first);
                }
                viz[x.first] = 1;
            }
        }
    }

    return 1;
}

int main() {
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        fin >> x >> y >> z;
        g[x].push_back(make_pair(y, z));
    }
    if (bellmanford()) {
        for (int i = 2; i <= n; i++) {
            fout << dist[i] << " ";
        }
    } else {
        fout << "Ciclu negativ!";
    }
}