Cod sursa(job #3376284)

Utilizator ungureanubogdanUngureanu Bogdan ungureanubogdan Data 17 noiembrie 2026 11:12:56
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <vector>
#include <queue>

std::ifstream cin("bellmanford.in");
std::ofstream cout("bellmanford.out");

int n, m;
std::vector<std::pair<int, int>> graf[100001];
int d[100001];
int in_queue[100001];
int lungime[100001];

bool bellman_ford() {
    for(int i = 1; i <= n; ++i) d[i] = lungime[i] = 1e9;
    int source = 1;
    d[source] = 0;

    std::queue<int> q;
    q.push(source);
    in_queue[source] = 1;
    lungime[source] = 0;

    while(!q.empty()) {
        int nod = q.front();
        q.pop();
        in_queue[nod] = false;
        
        for(auto nodnou : graf[nod]) {
            int cost = nodnou.first, dest = nodnou.second;
            if(d[nod] + cost >= d[dest]) continue;
            d[dest] = d[nod] + cost;
            
            lungime[dest] = lungime[nod] + 1;
            if(lungime[dest] >= n) return false;

            if(!in_queue[dest]) {
                q.push(dest);
                in_queue[dest] = true;
            }
            
        }        
    }

    return true;
}

int main() {
    cin >> n >> m;
    for(int i = 1; i <= m; ++i) {
        int x, y, cost;
        cin >> x >> y >> cost;
        graf[x].push_back({cost, y});
    }    

    if(bellman_ford()) {
        for(int i = 2; i <= n; ++i) {
            cout << d[i] << ' ';
        }
    }
    else {
        cout << "Ciclu negativ!";
    }

    return 0;
}