Cod sursa(job #3004804)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 16 martie 2023 16:55:51
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 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];
deque<int> q;
bool visited[DIM];

bool bellmanFord(int start) {
    dist[start] = 0;
    q.push_back(start);
    while (!q.empty()) {
        int node = q.front();
        q.pop_front();
        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!";
                        return false;
                    }

                    visited[adjNode] = true;
                    q.push_back(adjNode);
                }
            }
        }
    }
    return true;
}

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

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

    return 0;
}