Cod sursa(job #2721141)

Utilizator sichetpaulSichet Paul sichetpaul Data 11 martie 2021 16:34:32
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 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 dp[Nmax], upd[Nmax];
vector<pair<int, int> > G[Nmax];
queue<int> Q;
bool in[Nmax];
int main()
{
    fin >> N >> M;
    for (int i = 2; i <= N; ++i)
        dp[i] = INF;
    while (M--) {
        int x, y, c;
        fin >> x >> y >> c;
        G[x].push_back({y, c});
    }

    in[1] = 1, Q.push(1);
    while (!Q.empty()) {
        int node = Q.front();
        Q.pop();
        in[node] = 0;
        for (auto it: G[node]) {
            int nxt = it.first, dist = dp[node] + it.second;
            if (dist >= dp[nxt]) continue;
            dp[nxt] = dist;
            upd[nxt]++;
            if (in[nxt] == 0)
                Q.push(nxt), in[nxt] = 1;

            if (upd[nxt] == N) {
                fout << "Ciclu negativ!\n";
                return 0;
            }
        }
    }

    for (int i = 2; i <= N; ++i)
        fout << dp[i] << " ";

    return 0;
}