Cod sursa(job #3324183)

Utilizator KRISTY06Mateiu Ianis Cristian Vasile KRISTY06 Data 21 noiembrie 2025 16:01:55
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <fstream>
#include <bitset>
#include <queue>
#include <map>
using namespace std;

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

vector<pair<int, int>> graph[50001];

bitset<50001> isInQueue;

long long minDist[50001];

int noUpdates[50001];
int n, m;

bool negativeCycleFound;

void bfs(int startNode) {
    queue<int> q;
    q.push(startNode);
    isInQueue[startNode] = 1;
    minDist[startNode] = 0;
    while (!q.empty() && negativeCycleFound == 0) {
        int currentNode = q.front();
        q.pop();
        isInQueue[currentNode] = 0;
        if (noUpdates[currentNode] > n - 1) {
            negativeCycleFound = 1;
        }
        for (vector<pair<int, int>>::iterator it = graph[currentNode].begin(); it != graph[currentNode].end(); ++it) {
            if (minDist[currentNode] + it->second < minDist[it->first]) {
                ++noUpdates[it->first];
                minDist[it->first] = minDist[currentNode] + it->second;
                if (isInQueue[it->first] == 0) {
                    q.push(it->first);
                    isInQueue[it->first] = 1;
                }
            }
        }
    }
}

int main() {
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y, c;
        fin >> x >> y >> c;
        graph[x].push_back({y, c});
    }
    for (int i = 1; i <= n; ++i) {
        minDist[i] = 1e18;
    }
    bfs(1);
    if (negativeCycleFound == 0) {
        for (int i = 2; i <= n; ++i) {
            fout << minDist[i] << ' ';
        }
    } else {
        fout << "Ciclu negativ!";
    }
    return 0;
}