Cod sursa(job #3378697)

Utilizator mrvalentynTime Limit Exceeded mrvalentyn Data 27 noiembrie 2026 16:44:38
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
using namespace std;

const string FILENAME = "bellmanford";

#ifndef zz
ifstream f(FILENAME + ".in");
ofstream g(FILENAME + ".out");
#define cin f
#define cout g
#endif


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

int n,m;
int cnt[50001];
int inq[50001];

int main() {

    cin >> n >> m;

    for(int i=1;i<=m;++i) {
        int xx,yy,cc;
        cin >> xx >> yy >> cc;
        gg[xx].push_back({yy,cc});
    }

    vector<int> d(n + 1, INT_MAX);
    queue<int> q;
    d[1] = 0;
    q.push(1); inq[1] = 1;

    while(!q.empty()) {
        int v = q.front(); 
        q.pop();

        inq[v] = 0;

        for(auto edge : gg[v]) {
            int to = edge.first;
            int cst = edge.second;

            if(d[v] + cst < d[to]) {
                d[to] = d[v] + cst;
                if(!inq[to]) {
                    q.push(to);
                    inq[to] = 1;
                    cnt[to]++;

                    if(cnt[to] >= n) {
                        cout << "Ciclu negativ!\n";
                        return 0;
                    }
                }
            }
        }
    }

    for(int i=2;i<=n;++i) cout << d[i] << ' ';
 
    


    return 0;
}