Cod sursa(job #2711534)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 24 februarie 2021 12:30:57
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
//
// Created by mihai145 on 24.02.2021.
//

#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 50000;
const int INF = 1e9;

int N, M;
vector<pair<int, int>> g[NMAX + 5];

int impr[NMAX + 5], cost[NMAX + 5];
bool inQ[NMAX + 5];

int main() {
    cin >> N >> M;

    for (int i = 1; i <= M; i++) {
        int x, y, c;
        cin >> x >> y >> c;
        g[x].push_back({y, c});
    }

    for (int i = 1; i <= N; i++) {
        cost[i] = INF;
    }

    queue<int> q;
    q.push(1);
    cost[1] = 0;
    inQ[1] = true;

    while (!q.empty()) {
        int node = q.front();
        q.pop();
        inQ[node] = false;

        for (auto it : g[node]) {
            if (cost[it.first] > cost[node] + it.second) {
                cost[it.first] = cost[node] + it.second;
                if (!inQ[it.first]) {
                    q.push(it.first);
                    inQ[it.first] = true;

                    impr[it.first]++;
                    if (impr[it.first] > N) {
                        cout << "Ciclu negativ!\n";
                        return 0;
                    }
                }
            }
        }
    }

    for (int i = 2; i <= N; i++) {
        cout << cost[i] << ' ';
    }

    return 0;
}