Cod sursa(job #2884988)

Utilizator sichetpaulSichet Paul sichetpaul Data 5 aprilie 2022 12:40:54
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>
#define Nmax 50005
#define INF 1e9
using namespace std;

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

int N, M;
int dist[Nmax], upd[Nmax];
vector<pair<int, int> > G[Nmax];

int BellmanFord(int src) {
    queue<int> Q;
    Q.push(src);
    for (int i = 1; i <= N; ++i)
        dist[i] = INF;
    dist[src] = 0;

    while (!Q.empty()) {
        int node = Q.front();
        Q.pop();
        for (auto it: G[node]) {
            int nxt = it.first, newDist = it.second + dist[node];
            if (newDist < dist[nxt]) {
                ++upd[nxt];
                dist[nxt] = newDist;
                if (upd[nxt] == N) return 0;
                Q.push(nxt);
            }
        }
    }

    return 1;
}
int main()
{
    fin >> N >> M;
    while (M--) {
        int x, y, c;
        fin >> x >> y >> c;
        G[x].push_back({y, c});
    }

    int res = BellmanFord(1);
    if (res == 0) fout << "Ciclu negativ!\n";
    else {
        for (int i = 2; i <= N; ++i)
            fout << dist[i] << " ";
    }



    return 0;
}