Cod sursa(job #3246665)

Utilizator TeddyDinutaDinuta Eduard Stefan TeddyDinuta Data 3 octombrie 2024 22:04:03
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");

int n, m, x, y, c;

bool Bellman(int node, vector<vector<pair<int, int>>> &adj, vector<int> &dp) {
    queue<int> q;
    vector<bool> inq(n + 1, false);
    vector<int> cnt(n + 1, 0);

    q.push(node);
    dp[node] = 0;
    inq[node] = false;

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

        inq[nod] = false;

        for (auto it : adj[nod]) {
            if (dp[it.first] > dp[nod] + it.second) {
                cnt[it.first]++;
                dp[it.first] = dp[nod] + it.second;
                if (cnt[it.first] > n) {
                    return false;
                }

                if (!inq[it.first]) {
                    inq[it.first] = true;
                    q.push(it.first);
                }

            }
        }
    }

    return true;
}

int main() {
    in >> n >> m;
    vector<vector<pair<int, int>>> adj(n + 1, vector<pair<int, int>>());

    for (int i = 0; i < m; i++) {
        in >> x >> y >> c;
        adj[x].push_back({y, c});
    }

    vector<int> dp(n + 1, 1e9);

    if (Bellman(1, adj, dp)) {
        for (int i = 2; i <= n; i++) {
            out << dp[i] << " ";
        }
    } else {
        out << "Ciclu negativ!\n";
    }
    return 0;
}