Cod sursa(job #3272295)

Utilizator BogdancxTrifan Bogdan Bogdancx Data 29 ianuarie 2025 08:54:17
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <vector>
#include <queue>
#include <limits.h> // Pentru INT_MAX
#include <fstream>

using namespace std;

vector<int> bellman_ford(const vector<vector<pair<int, int>>>& graph, int n, int start) {
    vector<int> dist(n + 1, 1e9);
    vector<bool> visited(n + 1, false);
    vector<int> count(n + 1, 0);
    queue<int> q;

    dist[start] = 0;
    q.push(start);
    visited[start] = true;

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

        for (auto [neigh, w] : graph[node]) {
            if (dist[node] + w < dist[neigh]) {
                dist[neigh] = dist[node] + w;

                if (!visited[neigh]) {
                    q.push(neigh);
                    visited[neigh] = true;
                    count[neigh]++;

                    if (count[neigh] > n) {
                        cout << "Ciclu negativ!";
                        return {};
                    }
                }
            }
        }
    }

    return dist;
}

int main()
{
    ifstream fin("bellmanford.in");
    ofstream fout("bellmanford.out");
    int n, m;

    fin >> n >> m;

    vector<vector<pair<int, int>>> graph(n + 1);

    for (int i = 0; i < m; i++) {
        int a, b, c;
        fin >> a >> b >> c;
        graph[a].emplace_back(b, c);
    }

    vector<int> result = bellman_ford(graph, n, 1);

    if (!result.empty()) {
        for (int i = 2; i <= n; i++) {
            fout << result[i] << ' ';
        }
        fout << '\n';
    }

    return 0;
}