Cod sursa(job #2966505)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 17 ianuarie 2023 18:59:22
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <vector>
#include <utility>
#include <queue>

using namespace std;

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

const int DIM = 50001;
const int INF = 260000000;

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

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

    for (int i = 1; i <= n; i++)
        cost[i] = INF;

    q.push(1);
    cost[1] = 0;
    visited[1] = true;
    inQueue[1] = 1;
    while (!q.empty()) {
        int node = q.front();
        visited[node] = false;
        q.pop();

        for (auto adjElem : adjList[node]) {
            int adjNode = adjElem.first, currCost = adjElem.second;
            if (cost[adjNode] > cost[node] + currCost) {
                cost[adjNode] = cost[node] + currCost;
                if (!visited[adjNode]) {
                    inQueue[adjNode]++;
                    if (inQueue[adjNode] > n) {
                        fout << "Ciclu negativ!";
                        return 0;
                    }
                    q.push(adjNode);
                    visited[adjNode] = true;
                }
            }
        }
    }

    for (int i = 2; i <= n; i++)
        fout << cost[i] << ' ';

    return 0;
}