Cod sursa(job #3215754)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 15 martie 2024 12:29:52
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

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

const int DIM = 50010;

int n, m, x, y, c;
int dist[DIM], inQueue[DIM];
vector<pair<int, int>> l[DIM];
queue<int> q;
bool visited[DIM];

void bellman_ford(int start, bool& ok) {
    dist[start] = 0;
    q.push(start);
    visited[start] = true;
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        visited[node] = false;

        for (auto adjElem : l[node]) {
            int adjNode = adjElem.first;
            int adjDist = adjElem.second;
            if (dist[adjNode] > dist[node] + adjDist) {
                dist[adjNode] = dist[node] + adjDist;
                if (!visited[adjNode]) {
                    inQueue[adjNode]++;
                    if (inQueue[adjNode] > n) {
                        fout << "Ciclu negativ!";
                        ok = false;
                        return;
                    }
                    visited[adjNode] = true;
                    q.push(adjNode);
                }
            }
        }
    }
}

int main() {
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        l[x].emplace_back(y, c);
    }

    for (int i = 1; i <= n; i++)
        dist[i] = INT_MAX;

    bool ok = true;
    bellman_ford(1, ok);

    if (ok) {
        for (int i = 2; i <= n; i++)
            fout << dist[i] << ' ';
    }

    return 0;
}