Cod sursa(job #3295131)

Utilizator vladm98Munteanu Vlad vladm98 Data 2 mai 2025 15:16:55
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>

using namespace std;

vector <pair <int, int>> graph[50005];
int distances[50005];
int noOfNodes[50005];

void bellman(int source, int n) {
    for (int i = 1; i <= n; ++i) {
        distances[i] = 1e9;
    }
    queue <int> q;
    distances[source] = 0;
    noOfNodes[source] = 1;
    q.push(source);

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

        if (noOfNodes[node] > n) {
            // ciclu infinit
            cout << "Ciclu negativ!";
            exit(0); // opreste programul
        }

        for (auto x : graph[node]) {
            if (distances[x.first] > distances[node] + x.second) {
                distances[x.first] = distances[node] + x.second;
                noOfNodes[x.first] = noOfNodes[node] + 1;
                q.push(x.first);
            }
        }
    }
}

int main()
{
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        graph[u].push_back({v, w});
    }
    int source = 1;
    bellman(source, n);
    for (int i = 2; i <= n; i++) {
        cout << distances[i] << " ";
    }
    return 0;
}